我正在开发一个android应用程序,并且我有一个从源图像加载的可绘制程序。在此图像中,我想将所有白色像素转换为不同的颜色,例如蓝色,然后缓存生成的可绘制对象,以便稍后使用。
例如,假设我有一个20x20的PNG文件,中间有一个白色圆圈,圆圈之外的所有内容都是透明的。将白色圆圈变为蓝色并缓存结果的最好方法是什么?如果我想使用源图像创建几个新的Drawables (比如蓝色、红色、绿色、橙色等),答案是否会改变?
我猜我会想以某种方式使用ColorMatrix,但我不确定如何使用。
发布于 2009-11-11 22:52:04
我可以用下面的代码做到这一点,这段代码取自一个活动(布局非常简单,只包含一个ImageView,这里没有张贴)。
private static final int[] FROM_COLOR = new int[]{49, 179, 110};
private static final int THRESHOLD = 3;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_colors);
    ImageView iv = (ImageView) findViewById(R.id.img);
    Drawable d = getResources().getDrawable(RES);
    iv.setImageDrawable(adjust(d));
}
private Drawable adjust(Drawable d)
{
    int to = Color.RED;
    //Need to copy to ensure that the bitmap is mutable.
    Bitmap src = ((BitmapDrawable) d).getBitmap();
    Bitmap bitmap = src.copy(Bitmap.Config.ARGB_8888, true);
    for(int x = 0;x < bitmap.getWidth();x++)
        for(int y = 0;y < bitmap.getHeight();y++)
            if(match(bitmap.getPixel(x, y))) 
                bitmap.setPixel(x, y, to);
    return new BitmapDrawable(bitmap);
}
private boolean match(int pixel)
{
    //There may be a better way to match, but I wanted to do a comparison ignoring
    //transparency, so I couldn't just do a direct integer compare.
    return Math.abs(Color.red(pixel) - FROM_COLOR[0]) < THRESHOLD &&
        Math.abs(Color.green(pixel) - FROM_COLOR[1]) < THRESHOLD &&
        Math.abs(Color.blue(pixel) - FROM_COLOR[2]) < THRESHOLD;
}发布于 2011-04-30 04:41:26
我认为你实际上可以直接使用Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY )。这会将白色像素设置为红色,但我不认为它会影响透明像素。
请参阅Drawable#setColorFilter
发布于 2012-06-30 23:35:21
试一下这段代码:
ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);https://stackoverflow.com/questions/1309629
复制相似问题