如何改变一个可绘制的颜色的Andr​​oid?颜色、Andr、oid

由网友(遗憾也值得)分享简介:我工作的一个Android应用程序,而我有我从源图像装载了一个可绘制。在这个形象,我希望把所有的白色像素,以不同的颜色,说蓝,然后缓存所产生的可绘制对象,以便以后可以使用它。I'm working on an android application, and I have a drawable that I'm lo...

我工作的一个Android应用程序,而我有我从源图像装载了一个可绘制。在这个形象,我希望把所有的白色像素,以不同的颜色,说蓝,然后缓存所产生的可绘制对象,以便以后可以使用它。

I'm working on an android application, and I have a drawable that I'm loading up from a source image. On this image, I'd like to convert all of the white pixels to a different color, say blue, and then cache the resultant Drawable object so I can use it later.

因此​​,例如说我有,有一个白色的圆圈,中间一个20×20的PNG文件,以及外循环,一切都是透明的。什么是转了一圈白色的蓝色和缓存结果的最佳方式是什么?其答案是否改变,如果我想使用的源图像来创建一些新的可绘制(比如蓝,红,绿,橙等)?

So for example say I have a 20x20 PNG file that has a white circle in the middle, and that everything outside the circle is transparent. What's the best way to turn that white circle blue and cache the results? Does the answer change if I want to use that source image to create several new Drawables (say blue, red, green, orange, etc)?

我猜,我会想使用一个嘉洛斯以某种方式,但我不知道怎么样。

I'm guessing that I'll want to use a ColorMatrix in some way, but I'm not sure how.

推荐答案

我可以用下面的code,这是从一个活动(该布局是一个非常简单的,只包含一个ImageView的做到这一点,并没有张贴在这里)。

I was able to do this with the following code, which is taken from an activity (the layout is a very simple one, just containing an ImageView, and is not posted here).

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;
}
阅读全文

相关推荐

最新文章