Android图片着色问题

先看一下问题,原始图片是这样的,图片为白色 为了方便观察 父View的背景设置成了灰色

image.png

使用两个ImageView,一个不进行任何处理,一个用如下代码对图片进行着色

ImageView imageView = findViewById(R.id.iv_image_1);
Drawable drawable = imageView.getDrawable();
drawable.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP);

效果图如下:

image.png

明明只给一个Drawable进行着色,为什么两个ImageView都显示被着色后的Drawable?查资料后得出原因是Android的性能优化,资源Drawable内存中只有一份拷贝,对它着色就等于修改了所有的资源,将代码改成如下即可解决

ImageView imageView = findViewById(R.id.iv_image_1);
Drawable drawable = imageView.getDrawable();
Drawable wrap = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrap, getResources().getColor(R.color.colorAccent));

改完后效果图


image.png

你可能感兴趣的:(Android图片着色问题)