Android apply colorMatrix colorFilter on part of imageView with a mask

家住魔仙堡 提交于 2019-12-03 01:29:47

for given bitmap and mask:

first create a temporary bitmap:

bitmap = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.bitmap);
mask = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.mask);

float[] src = {
    0, 0, 0, 0, 255,
    0, 0, 0, 0, 255,
    0, 0, 0, 0, 255,
    1, 1, 1, -1, 0,
};
ColorMatrix cm = new ColorMatrix(src);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(cm);
maskPaint = new Paint();
maskPaint.setColorFilter(filter);
maskPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

filteredBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(filteredBitmap);
c.drawBitmap(bitmap, 0, 0, null);
c.drawBitmap(mask, 0, 0, maskPaint);

colorFilterPaint = new Paint();
colorFilterPaint.setColorFilter(new LightingColorFilter(0xffffff, 0x880000));

and draw it (I scaled it up since my emulator scaled it down):

@Override
public void draw(Canvas canvas) {
    canvas.save();
    canvas.scale(3, 3);
    canvas.drawBitmap(bitmap, 0, 0, null);
    canvas.drawBitmap(filteredBitmap, 0, 0, colorFilterPaint);
    canvas.restore();
}

and the result is:

You may change

float[] src = {
0, 0, 0, 0, 255,
0, 0, 0, 0, 255,
0, 0, 0, 0, 255,
1, 1, 1, -1, 0,
};

to

float[] src = {
0, 0, 0, 0, 255,
0, 0, 0, 0, 255,
0, 0, 0, 0, 255,
1, 1, 1, 0, 0,
};

to give more semi-transparency at gray part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!