Draw rectangle with XML shape settings in Android

别说谁变了你拦得住时间么 提交于 2019-12-19 10:53:02

问题


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?


回答1:


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

}


来源:https://stackoverflow.com/questions/12821416/draw-rectangle-with-xml-shape-settings-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!