我在一个android应用程序上工作,我有一个可绘制的,我正在从源图像加载。在这个图像上,我想将所有的白色像素转换为不同的颜色,比如蓝色,然后缓存生成的Drawable对象,以便以后使用它。

例如,我有一个20x20的PNG文件,中间有一个白色的圆圈,圆圈之外的一切都是透明的。把白色圆圈变成蓝色并缓存结果的最好方法是什么?如果我想使用源图像来创建几个新的Drawables(比如蓝色、红色、绿色、橙色等),答案会改变吗?

我猜我想在某种程度上使用一个ColorMatrix,但我不确定如何。


当前回答

根据isWorking字段更改可绘制颜色的简短示例。

我的形状xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_bright" />
    <corners android:radius="30dp" />
    <size
        android:height="15dp"
        android:width="15dp" />
</shape>

我的改变方法:

private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
    Drawable d = getResources().getDrawable(R.drawable.shape);
    ColorFilter filter = new LightingColorFilter(
            isworking ? Color.GREEN : Color.RED,
            isworking ? Color.GREEN : Color.RED);
    d.setColorFilter(filter);
    return d;
}

用法示例:

text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);

其他回答

我知道这个问题是在棒棒糖之前问的,但我想在Android 5上添加一个很好的方法来做到这一点。你创建了一个引用原始图形的xml绘图,并像这样设置着色:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

根据isWorking字段更改可绘制颜色的简短示例。

我的形状xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_bright" />
    <corners android:radius="30dp" />
    <size
        android:height="15dp"
        android:width="15dp" />
</shape>

我的改变方法:

private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
    Drawable d = getResources().getDrawable(R.drawable.shape);
    ColorFilter filter = new LightingColorFilter(
            isworking ? Color.GREEN : Color.RED,
            isworking ? Color.GREEN : Color.RED);
    d.setColorFilter(filter);
    return d;
}

用法示例:

text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);

我只是遇到了这个问题,并通过替换来解决它:

android:tint="@color/yellow_800"

到以下

app:tint="@color/yellow_800"

Koltin解决方案使用视图绑定:

binding.avatar.drawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(R.color.white, BlendModeCompat.SRC_ATOP)

这使用了最新版本的核心androidx库。

有这么多的解决方案,但没有人建议,如果颜色资源xml文件已经有颜色,那么我们可以直接从那里也如下所示:

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));