0

square_transparent.png

我事先创建了一个可绘制的对象,它是一个矩形,但完全透明。现在我想将此drawable分配给代码中的Button,但还将此drawable的颜色从透明设置为某种特定颜色,例如橙色等。

我已经尝试使用其他一些帖子进行设置,例如 -

Drawable mDrawable = ContextCompat.getDrawable(this, R.drawable.square_transparent); 
    mDrawable.setColorFilter(
                    new PorterDuffColorFilter(
                            Color.Orange, Mode.SRC_IN)
                            );

但它不起作用。当活动呈现按钮时,它仍然是透明的。

在将可绘制对象分配给按钮之前,我还尝试将 mDrawable.setAlpha 显式设置为 255(完全不透明),但即使这样也不起作用。

请建议,如果有人以其他方式进行此工作。

4

3 回答 3

0

最后,我使用 2 步解决方案得到了最终结果 -

  1. 我将可绘制对象从透明的固定到没有不透明度的纯白色(似乎颜色过滤/着色,在白色上效果最好)

  2. 我还使用下面的代码行来做到这一点 -

        Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.yourcustomshape, null);
    
        drawable = DrawableCompat.wrap(drawable);
    
        DrawableCompat.setTintList(drawable, ColorStateList.valueOf(Color.BLUE)); // Can be any color you need to color the shape
    
于 2015-08-29T22:42:56.453 回答
0

使用两种方法可以设置背景颜色和边框

这对于没有背景颜色

public static GradientDrawable backgroundWithoutBorder(int color) {

        GradientDrawable gdDefault = new GradientDrawable();
        gdDefault.setColor(color);
        gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                radius, radius });
        return gdDefault;

    }

这与背景颜色

    public static GradientDrawable backgroundWithBorder(int bgcolor,
            int brdcolor) {

        GradientDrawable gdDefault = new GradientDrawable();
        gdDefault.setColor(bgcolor);
        gdDefault.setStroke(2, brdcolor);
        gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                radius, radius });

        return gdDefault;

    }
于 2015-09-11T19:25:35.713 回答
0

使用Mode.SRC而不是Mode.SRC_IN.

有关详细信息,请参阅PorterDuff 模式

于 2015-08-22T23:43:24.533 回答