我有一个带有位图的 ImageView。此位图具有 alpha channel 和透明像素。 当我尝试将 ColorFiter 与 Mode.OVERLAY(自蜂窝)一起使用时 - 提供颜色覆盖整个 ImageView (整个矩形),但我只想覆盖非透明像素。我如何裁剪 imageview 的 Canvas 以在我想要的地方执行过滤器?
已更新
我在 png 中有灰色图像:
当我尝试使用 MODE_ATOP 时,我得到:
当我使用 OVERLAY 时,我得到:
以及我想要得到的:
最佳答案
可能有更有效的方法来做到这一点(可能通过创建一个 ColorMatrixColorFilter
来近似它),但由于 Mode.OVERLAY
似乎是 hard to simplify otherwise ,这里有一些示例代码应该实现你想要的:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ImageView imageView = new ImageView(this);
setContentView(imageView);
final Paint paint = new Paint();
Canvas c;
final Bitmap src = BitmapFactory.decodeResource(getResources(),
android.R.drawable.sym_def_app_icon);
final int overlayColor = Color.RED;
final Bitmap bm1 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
c = new Canvas(bm1);
paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.OVERLAY));
c.drawBitmap(src, 0, 0, paint);
final Bitmap bm2 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
c = new Canvas(bm2);
paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.SRC_ATOP));
c.drawBitmap(src, 0, 0, paint);
paint.setColorFilter(null);
paint.setXfermode(new AvoidXfermode(overlayColor, 0, Mode.TARGET));
c.drawBitmap(bm1, 0, 0, paint);
imageView.setImageBitmap(bm2);
}
}
简而言之,我们使用OVERLAY
模式绘制源位图和颜色,然后使用辅助位图(使用SRC_ATOP
模式合成),我们使用AvoidXfermode
组合它不绘制透明像素。
原图:
结果:
关于android - 非透明像素上的 ImageView 颜色过滤器。夹子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968040/