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

标签 android android-drawable

如何在 XML 资源文件中创建此可绘制对象? 我已尝试使用图层列表可绘制对象,但在缩放箭头资源时遇到问题。

有没有更简单的方法?

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

最佳答案

试试这个:

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

关于android - 如何在Android中创建这个稍微复杂的XML Drawable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26429584/

相关文章:

android - Google Glass - 每个应用程序都需要向 Google 注册语音触发器吗?

安卓工作室 : Drawable Folder: How to put Images for Multiple dpi?

Android - 如何修复 EditText 左侧的卢比符号字体图标

android - 弧形矩形机器人

android - 向 ImageView 添加渐变

java - Android CountDownTimer 中的 .cancel() 问题

android - 尝试在设备上绘制带纹理的三角形失败,但模拟器可以运行。为什么?

java - 如何以编程方式根据文件名设置 Drawable

android - 显示对话框时出现 java.lang.IllegalStateException 错误

android - 按钮文本旋转与标签 singleLine 不正确