如何在 Android 中更改 Drawable 的颜色? [英] How to change colors of a Drawable in Android?

查看:251
本文介绍了如何在 Android 中更改 Drawable 的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 android 应用程序,我有一个可从源图像加载的 drawable.在这张图片上,我想将所有白色像素转换为不同的颜色,比如蓝色,然后缓存生成的 Drawable 对象,以便我以后可以使用它.

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.

例如,假设我有一个 20x20 PNG 文件,中间有一个白色圆圈,圆圈外的所有内容都是透明的.将白色圆圈变为蓝色并缓存结果的最佳方法是什么?如果我想使用该源图像创建多个新的 Drawable(例如蓝色、红色、绿色、橙色等),答案是否会改变?

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)?

我猜想以某种方式使用 ColorMatrix,但我不确定如何使用.

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

推荐答案

我可以使用以下代码来完成此操作,该代码取自 Activity(布局非常简单,仅包含一个 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;
}

这篇关于如何在 Android 中更改 Drawable 的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆