Draw rectangle with XML shape settings in Android

Alex  Zezekalo picture Alex Zezekalo · Oct 10, 2012 · Viewed 14.6k times · Source

I've got a problem which I don't know how to solve. Please, help me if you can. In my app I have to create a custom view extended View. In this view I should draw a lot of rectangles and I create them by canvas.drawRect or canvas.drawRoundRect. It's clear. But I want to create a compound design of these rectangles (with gradients, corners, paddings and etc.) and I want to carry out these settings (gradients, corners, paddings and etc.) in XML. How can I do it? The problem is that I determine shape in XML I can use this drawable only as background but when I draw a rectangle I can't set background for rectangle. Maybe there are another way to solve the problem. Could I use the XML shape object for setting not only as background but a view object with x,y-coordinates and width, height?

Edit: I can draw rectangle:

canvas.drawRect(x1, y1, x2, y2, paint);

but I have rectangle settings in XML like this:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

<!-- Specify a gradient for the background -->
    <gradient
    android:angle="90"
    android:startColor="#55000066"
    android:centerColor="#FFFFFF"
    android:endColor="#55000066" />

<!-- Specify a dark blue border -->
    <stroke 
    android:width="2dp"
    android:color="#000066" />

<!-- Specify the margins that all content inside the drawable must adhere to -->
    <padding
    android:left="5dp"
    android:right="5dp"
    android:top="5dp"
    android:bottom="5dp" />

<corners
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="10dp" />
</shape>

and I want to apply this settings to my rectangle. How?

Answer

nEx.Software picture nEx.Software · Oct 10, 2012

You can load and use the XML defined drawable from code like so:

public class CustomView extends View {

    Drawable shape;

    public CustomView(Context context) {
        super(context);
        shape = context.getResources().getDrawable(R.drawable.shape);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        shape.setBounds(left, top, right, bottom);
        shape.draw(canvas)
    }

    // ... Additional methods omitted for brevity

}