如何用 Android 中的颜色填充黑白 PNG 图标?
How to fill a B&W PNG icon with a color in Android?
我想用颜色填充 PNG 图标。
这是我当前的代码:
ingredientImageView.setImageResource(context.getResources().getIdentifier("ico_" + ingredient.replace("-", "_"), "drawable", context.getPackageName()));
ingredientImageView.setColorFilter(iconTextColor,PorterDuff.Mode.SRC_IN);
这段代码让我的图标变成这样:
iconTextColor 这里是黑色的。但是滤色器填充了图标的白色部分。您可以在下面找到图标:
黑线应该变成我想要的颜色。但是叶子内部(在那个图标中)应该保持白色。
所以,透明->透明,白色->白色,黑色->动态颜色
我该怎么做?
您不能更改 .png 图标的颜色,但可以更改 xml 形式的矢量图标的颜色。
要更改图标的颜色,只需导入不同颜色的图标即可。
您可以尝试使用随机 r g b 值定义自定义 ColorMatrix:
Random rand = new Random();
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
1, 0, 0, 0, r,
0, 1, 0, 0, g,
0, 0, 1, 0, b,
0, 0, 0, 1, 0 }); // last line is antialias
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(myBitmap, toX, toY, paint);
我不太确定你的问题,但每当我需要更改 .png 图像的颜色时,我只是使用 tint 方法。您可以查看以下代码以获取帮助
XML 代码
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ss"
android:tint="@color/colorPrimary"
/>
java代码
getBackground().setTint(tintColor);
我想用颜色填充 PNG 图标。
这是我当前的代码:
ingredientImageView.setImageResource(context.getResources().getIdentifier("ico_" + ingredient.replace("-", "_"), "drawable", context.getPackageName()));
ingredientImageView.setColorFilter(iconTextColor,PorterDuff.Mode.SRC_IN);
这段代码让我的图标变成这样:
iconTextColor 这里是黑色的。但是滤色器填充了图标的白色部分。您可以在下面找到图标:
黑线应该变成我想要的颜色。但是叶子内部(在那个图标中)应该保持白色。
所以,透明->透明,白色->白色,黑色->动态颜色
我该怎么做?
您不能更改 .png 图标的颜色,但可以更改 xml 形式的矢量图标的颜色。 要更改图标的颜色,只需导入不同颜色的图标即可。
您可以尝试使用随机 r g b 值定义自定义 ColorMatrix:
Random rand = new Random();
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
1, 0, 0, 0, r,
0, 1, 0, 0, g,
0, 0, 1, 0, b,
0, 0, 0, 1, 0 }); // last line is antialias
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(myBitmap, toX, toY, paint);
我不太确定你的问题,但每当我需要更改 .png 图像的颜色时,我只是使用 tint 方法。您可以查看以下代码以获取帮助
XML 代码
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ss"
android:tint="@color/colorPrimary"
/>
java代码
getBackground().setTint(tintColor);