我需要以编程方式创建此形状(我需要根据用户选择更改其笔触颜色)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"   android:shape="oval" >
<solid
    android:color="#FFEECC"
    />
<size
    android:width="100dp"
android:height="100dp"
/>

<stroke android:width="5dp" android:color="#444444" />


</shape>

我尝试使用 ShapeDrawable 但它似乎没有笔触颜色选项?此外,无论您为它们设置什么宽度或高度,形状都会倾向于拉伸(stretch)?谁能解释一下?

试过这个
ShapeDrawable sd = new ShapeDrawable();
            sd.setShape(new OvalShape());
            sd.getPaint().setStrokeWidth(20);
            sd.getPaint().setColor(Color.RED);

最佳答案

出于某种原因,您需要使用 GradientDrawable(强制使用纯色而不是真正的渐变):

    int backgroundColor = Color.RED;
    int strokeColor = Color.GRAY;
    int strokeSize = 10;
    GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{backgroundColor, backgroundColor});
    drawable.setShape(GradientDrawable.OVAL);
    drawable.setStroke(strokeSize, strokeColor);
    //...use your drawable

这是你使用上面的代码得到的:

为了实现 阴影效果 ,使用高程属性或创建一个带有阴影层的 LayerListDrawable

关于android - 如何在 Android 中以编程方式/动态方式创建此 shape.xml。设置笔触颜色(包括图片/代码),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31366560/

10-12 01:39
查看更多