2

嗨,我有一个可在 xml 中绘制的形状,它用作视图的背景。它的颜色需要根据条件在代码中更改。

所以我在做

  ShapeDrawable d =  (ShapeDrawable) getResources().getDrawable(R.drawable.shape1);

  d.getPaint().setShader(sd1);

但是 getDrawable 返回一个渐变可绘制对象,将其转换为 ShapeDrawable 会产生错误。

那么如何在代码中获取 shapeDrawable 并修改其属性。

4

4 回答 4

1

我可以通过转换为 GradientDrawable 而不是 ShapeDrawable 来解决这个问题。

GradientDrawable shape = (GradientDrawable) getResources().getDrawable(R.drawable.shape1);

    shape.setColor(Color);

当我使用基于 Holo.Dialog 主题的自定义样式创建活动时,我使用了它。

于 2014-06-25T10:09:51.630 回答
1

此代码段对我有用:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)
于 2017-05-23T07:16:53.753 回答
0

以下是设置颜色的方法:

d.getPaint().setColor(Color.BLACK);
于 2013-08-13T15:21:15.050 回答
0

我编写了一个通用函数,您可以在其中传递上下文,图标是 id 可绘制/mipmap 图像图标和该图标所需的新颜色。

这个函数返回一个drawable。

public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
    Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate(); 
    mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)); 
    return mDrawable;
} 

changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);
于 2017-03-22T07:15:40.150 回答