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

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

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


当前回答

你应该为所有api这样做:

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

其他回答

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

android:tint="@color/yellow_800"

到以下

app:tint="@color/yellow_800"

这段代码片段对我来说很有用:

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

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

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

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

试着android: backgroundTint = " @color / quantum_black_100”

会帮助那些想要完全改变Drawable颜色的人吗

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_memory"
    android:backgroundTint="@color/lime" />