如何在Android中创建这个稍微复杂的XML Drawable?

时间:2014-10-17 16:37:17

标签: android android-drawable

如何在XML资源文件中创建此drawable? 我尝试过使用图层列表可绘制但我在缩放箭头资源方面遇到了问题。

有更简单的方法吗?

<?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

1 个答案:

答案 0 :(得分:2)

试试这个:

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);
    }
}

示例代码(将其添加到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)));

结果:

enter image description here