Create Diagonal Cut View in Android


Rotate. View. background.



Recently, my friend create a detailed post on how to make diagonal shape view in Android. In that post, he detailed every step to create a custom view to achieve that shape. But, I wonder, if I create that without creating custom view and by using background only. Turn out, I can do that, by rotating the layer-list item.


diagonal cut view concept

Let’s jump into code and create the view :
  • Create a simple layout
<RelativeLayout
    android:id="@+id/background"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:background="@drawable/background" />
  • Now we need to create the @drawable/background. Create new drawable resource file. Delete generated code, and replace it with layer-list.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
</layer-list>
Layer list basically like a layer in image editor software. We can put as many layer (item) inside layer-list and then position and manipulate them. The difference is the layer arrangement, the lower item will be placed in front of its upper.
We can create an item with rectangle shape, solid fill and then rotate it upward, like in first gif. But, because I want to achieve like in first image, I want to rotate the lowest / frontmost item. The structure of layers will be like this :
- a drawable item with a color
- an item that contain a bitmap (image)
- a shape item that we will rotate
  • Drawable item with color
<item android:drawable="@color/colorPrimary"/>
  • Bitmap item with alpha for a nice “tint” like effect.
<item>
    <bitmap android:src="@drawable/bebe" android:gravity="center" android:alpha="0.1"/>
</item>
  • A shape to rotate, we want our rectangle to be placed on the other items.

Top, Left, Bottom and Right is like padding. Top value= layout height (it’s a good practice to put this inside dimen resource). Bottom with minus value, so the shape is drawn to bottom, not up. Minus value for right means the shape will be drawn far right from app border. This is important, otherwise we will see the shape border, like this :


Rotate is for manipulating the rotation of its child. FromDegrees is the rotation degree, its value is -10 because we want to rotate up by 10 degree. (there’s toDegrees attribute, but we don’t need it because we won’t animate the rotation). PivotX and PivotY is the rotation point / anchor.
Create a rectangle shape and fill it with colour of the app background.
Putting it all together, this is the background.xml :


Full code :click here

Comments

Popular posts from this blog

HashMaps, ArrayMaps and SparseArrays in Android

25 Life Lessons I’ve Learned In 25 Years