我在一个android应用程序上工作,我有一个可绘制的,我正在从源图像加载。在这个图像上,我想将所有的白色像素转换为不同的颜色,比如蓝色,然后缓存生成的Drawable对象,以便以后使用它。
例如,我有一个20x20的PNG文件,中间有一个白色的圆圈,圆圈之外的一切都是透明的。把白色圆圈变成蓝色并缓存结果的最好方法是什么?如果我想使用源图像来创建几个新的Drawables(比如蓝色、红色、绿色、橙色等),答案会改变吗?
我猜我想在某种程度上使用一个ColorMatrix,但我不确定如何。
我在一个android应用程序上工作,我有一个可绘制的,我正在从源图像加载。在这个图像上,我想将所有的白色像素转换为不同的颜色,比如蓝色,然后缓存生成的Drawable对象,以便以后使用它。
例如,我有一个20x20的PNG文件,中间有一个白色的圆圈,圆圈之外的一切都是透明的。把白色圆圈变成蓝色并缓存结果的最好方法是什么?如果我想使用源图像来创建几个新的Drawables(比如蓝色、红色、绿色、橙色等),答案会改变吗?
我猜我想在某种程度上使用一个ColorMatrix,但我不确定如何。
当前回答
会帮助那些想要完全改变Drawable颜色的人吗
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_memory"
android:backgroundTint="@color/lime" />
其他回答
在你的活动中,你可以用一种颜色来着色你的PNG图像资源:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myColorTint();
setContentView(R.layout.activity_main);
}
private void myColorTint() {
int tint = Color.parseColor("#0000FF"); // R.color.blue;
PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
// add your drawable resources you wish to tint to the drawables array...
int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
for (int id : drawables) {
Drawable icon = getResources().getDrawable(id);
icon.setColorFilter(tint,mode);
}
}
当你使用r。drawable时。它应该用所需要的颜色着色。如果你需要额外的颜色,那么你应该能够.mutate()绘制。
我也使用ImageView图标(在ListView或设置屏幕)。但我认为有更简单的方法。
使用着色来改变所选图标上的颜色叠加。
在xml中,
android:tint="@color/accent"
android:src="@drawable/ic_event"
工作很好,因为它来自AppCompat
它适用于一些简单的绘图。我用它在一个简单的纯色矩形圆角形状和需要改变的颜色与不同的布局。
试试这个
android:backgroundTint="#101010"
view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY);
谢谢@sabadow
如果你有一个纯色的可绘制对象,你想把它改成不同的纯色,你可以使用ColorMatrixColorFilter。透明度得以保留。
int iColor = Color.parseColor(color);
int red = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue = iColor & 0xFF;
float[] matrix = { 0, 0, 0, 0, red,
0, 0, 0, 0, green,
0, 0, 0, 0, blue,
0, 0, 0, 1, 0 };
ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);