How do I create this slightly complex XML Drawable in Android?

How do I create this resource in an XML resource file? I've tried using draw-list, but I'm having trouble scaling the arrow resources.

Is there an easier approach?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/accent_blue" />
            <size android:width="@dimen/circle_thermostat_diameter_large" android:height="@dimen/circle_thermostat_diameter_large" />
        </shape>
    </item>

    <item>
        <bitmap android:src="@drawable/arrow_up" android:gravity="center"/>
    </item>

    <!-- ... -->

</layer-list>

      

enter image description here

+3


source to share


1 answer


try this:

class S extends Shape {
    Path path = new Path();
    float size;

    S(float size) {
        this.size = size;
    }

    @Override
    protected void onResize(float width, float height) {
        float radius = Math.min(width, height) / 2;
        path.reset();
        path.moveTo(width / 2 - size, height / 2 - radius / 2);
        path.rLineTo(size, -size);
        path.rLineTo(size, size);

        path.moveTo(width / 2 - size, height / 2 + radius / 2);
        path.rLineTo(size, size);
        path.rLineTo(size, -size);
    }

    @Override
    public void draw(Canvas canvas, Paint paint) {
        float w = getWidth();
        float h = getHeight();
        float radius = Math.min(w, h) / 2;
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLUE);
        canvas.drawCircle(w / 2, h / 2, radius, paint);

        paint.setStrokeWidth(size / 4);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.WHITE);
        canvas.drawPath(path, paint);
    }
}

      

example code (add it to onCreate):



TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
float size = 128;
tv.setTextSize(size);
tv.setTextColor(Color.WHITE);
tv.setText("72");
setContentView(tv);
tv.setBackground(new ShapeDrawable(new S(size / 2)));

      

result:

enter image description here

+2


source







All Articles