4

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.

3 Answers3

1

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"
j2emanue
  • 60,549
  • 65
  • 286
  • 456
0

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

Community
  • 1
  • 1
cylon
  • 735
  • 1
  • 11
  • 26
  • Thanks for your response but how can I change stroke width for left and right edge of rectangle? – user2124933 Dec 16 '15 at 22:10
  • I don't know if that is possible. Maybe you should implement a layer-list, with a rectangle, and 4 lines. Then you can modify those line's stroke value differently from each other. – cylon Dec 16 '15 at 22:18
  • Can you please point me to some example? That would be really helpful. – user2124933 Dec 16 '15 at 22:23
0

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