我定义了一个像这样的Android 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="@android:color/transparent" />
<stroke android:width="8dp" android:color="@android:color/white" />
</shape>
</item>
<item android:left="2dp" android:bottom="2dp" android:right="2dp" android:top="2dp">
<shape android:shape="oval">
<solid android:color="@android:color/transparent" />
<stroke android:width="4dp" android:color="@android:color/black" />
</shape>
</item>
</layer-list>
在代码中,我从资源中获取drawable并在画布上绘制时使用它(SurfaceView.draw)。
Drawable dr = context.getResources().getDrawable(R.drawable.circle_empty);
@Override
public void draw(Canvas canvas) {
// how to set the color?
dr.draw(canvas);
}
但我想知道,我怎么能改变代码中drawable的颜色?例如,获取绿色或红色环,而不是XML中定义的黑色环。
答案 0 :(得分:0)
尝试这样的事情:
LayerDrawable layerDrawable= (LayerDrawable) context.getResources().getDrawable(R.drawable.circle_empty);
GradientDrawable gradientDrawable= (GradientDrawable)layerDrawable.getDrawable(1);
gradientDrawable.setStroke(4, Color.GREEN);