Skip to content

Create Triangle Shape Using XML In Android

  • by

Here in this article lets how to create a triangle shape using XML shape. No images needed for this method. With few lines of code we can create a triangle shape with desired color.

Shape class only allows for creating rectangular and circular shapes. But with trick we can create triangle.

It is very useful if you want a pointer like images. I explain this because such an image is very common in many places.

Step 1. Create Triangle Shape Drawable

  • Create a file shape_triangle.xml under res/drawable
  • Copy Paste the content below Into Drawable File
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate android:fromDegrees="45" android:toDegrees="45" android:pivotX="-40%" android:pivotY="87%" >
            <shape android:shape="rectangle" >
                <stroke android:color="#c6802a" android:width="10dp"/>
                <solid android:color="#c6802a" />
            </shape>
        </rotate>
    </item>
</layer-list>

In the above code it will create a rectangular shape and rotates. When we add rectangular shape under it will rotate with given degree. Here rotation is from 45 degree to 45 degree. Also define x and y coordinates of pivot of the rectangle, this will hide rest of the portion of rectangle invisible and make shape triangle.

Step 2: Usage In Activity Layout XML

Set this shape as src of an ImageView in res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" android:layout_height="match_parent" 
  android:paddingBottom="@dimen/activity_vertical_margin" 
  android:paddingLeft="@dimen/activity_horizontal_margin" 
  android:paddingRight="@dimen/activity_horizontal_margin" 
  android:paddingTop="@dimen/activity_vertical_margin">

<ImageView 
    android:layout_width="220dp" 
    android:layout_height="220dp" 
    android:layout_centerInParent="true" 
    android:layout_marginBottom="10dp" 
    android:rotation="180" 
    android:src="@drawable/shape_triangle" />

</RelativeLayout>

Step 3. Run The Application

run_triangle_shape

The rotation will decide whether this triangle will look like head down or head up fashion. This rotation can be set to any degree according to your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *