user2124933
user2124933

Reputation: 61

How to draw a Android Shape Rectangle with variable stroke width

I want to draw a rectangle with a hole in it. I am trying to achieve this by using Shape Rectangle.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="50dp"
        android:color="@color/red" />
</shape>

I am trying to figure out how can I change stroke width while this rectangle is being drawn so that Rectangle shall have for example: 50 dp stroke width on top and bottom edges but 20 dp on left and right edges.

I really appreciate your help on this.

Upvotes: 4

Views: 2484

Answers (3)

user2124933
user2124933

Reputation: 61

Thanks all for your help. I ended up overriding onDraw() to clear out background color of layout to create rectangular hole using setXfermode().

Upvotes: 0

j2emanue
j2emanue

Reputation: 62519

Here is an example of how you can do it with a layer-list: I'll change the top left and right attributes like this:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>

    <item android:top="1dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/holo_blue_bright"/>
        </shape>
    </item>

    <item android:left="3dp">
        <shape android:shape="rectangle">
            <gradient android:angle="270" android:startColor="#8C2300" android:endColor="#D34617"/>
        </shape>
    </item>

    <item android:right="8dp">
        <shape android:shape="rectangle">
            <gradient android:angle="270" android:startColor="#000000" android:endColor="#ffc0cb"/>
        </shape>
    </item>

</layer-list>

call this file something like layers.xml in your drawable folder. then apply it as a background to your view like this:

android:background="@drawable/shape"

Upvotes: 1

cylon
cylon

Reputation: 733

I assume, the shape is used as a background of a view (e.g. imageView). So first get the Drawable object from the imageView and get the Paint object from it. Then you can modify any property that you want.

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable)background;
    shapeDrawable.getPaint().setStrokeWidth(...);
}

Related question here: Set android shape color programmatically

Upvotes: 0

Related Questions