[Android] 修改ImageView的图片颜色

有两种方法:

方法1:

ImageView imageView = (ImageView) findViewById(R.id.arrow_image);
Drawable tipsArrow = imageView.getDrawable();                    
tipsArrow.setColorFilter(mContext.getResources().getColor(R.color.red_bg1), PorterDuff.Mode.SRC_ATOP);
imageView.setImageDrawable(tipsArrow);

 

方法2:

ImageView imageView = (ImageView) findViewById(R.id.arrow_image);
Bitmap baseBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.img_pop_arrow);
Bitmap afterBitmap = Bitmap.createBitmap(baseBitmap.getWidth(), baseBitmap.getHeight(), baseBitmap.getConfig());
Canvas canvas = new Canvas(afterBitmap);
Paint paint = new Paint();
float[] src = new float[]{
    0, 0, 0, 0, 253,
    0, 0, 0, 0, 54,
    0, 0, 0, 0, 102,
    0, 0, 0, 1, 0
};
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.set(src);
paint.setColorFilter(new ColorMatrixColorFilter(src));
canvas.drawBitmap(baseBitmap, new Matrix(), paint);
imageView.setImageBitmap(afterBitmap);

 

方法1比方法2更加简洁,但会有个问题,如果同个activity里面,有多个ImageView,每个ImageView操作的图片路径都是一样的,那么它们是会互相影响的。

比如,第一个ImageView要将图片设置为绿色,第二个ImageView要将图片设置为红色,那么出来的结果就是有问题,两张都变成绿色了。

 

方法2虽然比方法1复杂,但可以避免以上问题。同时它使用了ColorMatrix,这是个有趣的东西,值得深入研究,这里就不展开说。

 

Have fun with Android!

posted @ 2016-11-12 14:06  DavidHHuan  阅读(1285)  评论(0编辑  收藏  举报