使所有彩色像素不透明

时间:2014-08-30 22:56:19

标签: android colors colormatrix colormatrixfilter

我正在使用一些Android资源,例如ic_menu_camera.png

enter image description here

图像具有透明背景(所需),但在彩色像素中也有一些透明度(不需要)。

我使用ColorMatrixColorFilter对这些图像应用色调并且工作正常,但是,图标中的少量透明度会导致底层背景渗透,并使颜色褪色。我无法找到一种将所有彩色像素设置为不透明的编程方式。有什么帮助吗?

当前着色代码:

public static void colorImageView(Context context, ImageView imageView, @ColorRes int colorResId) {
    Drawable drawable = imageView.getDrawable();
    int color = context.getResources().getColor(colorResId);

    drawable.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(new float[] {
            0, 0, 0, 0, Color.red(color),
            0, 0, 0, 0, Color.green(color),
            0, 0, 0, 0, Color.blue(color),
            0, 0, 0, 1, 0,
    })));
}

目前的结果:

enter image description here

(第一个图标的源图像是不透明的,而另外3个图像具有不希望的透明度,导致这种偏蓝色)

1 个答案:

答案 0 :(得分:2)

首先出现了一个非常简单的方法: 也许您可以将Drawable转换为位图并执行所需的像素操作(如此answer),例如:

for(int x = 0; x < bitmap.getWidth(); x++) {
    for(int y = 0; y < bitmap.getHeight(); y++) {
        int pixel = bitmap.getPixel(x, y);
        int r = Color.red(pixel), g = Color.green(pixel), b = Color.blue(pixel);
        if (r != 0 || g != 0 || b != 0)
        {
            pixel.setPixel(x, y, Color.rgb(r, g, b));
        }
    }
}

删除每个像素中的任何alpha通道值,其r-,g-或b-值大于零。

但我不知道,这种方法有多么差或慢。我认为使用像素操作转换为位图可能比ColorMatrixColorFilter慢得多。