Android applies colorMatrix colorFilter on part of imageView with mask

I want to change the brightness on a certain part of the image. I know how to use ColorMatrix to change the brightness (or hue) of an image. But this will apply to the whole image.

I have a mask file (black and white image). I want to apply a brightness change only to the white part of this mask. How to do it in Android?

Below is the image of the mask and the result that I want to get.

enter image description hereenter image description here

+7
source share
2 answers

for a given bitmap and mask:

bitmap.png

mask.png

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 expanded it, as my emulator reduced it):

 @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:

enter image description here

+11
source

You can 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 get more translucency in the gray part.

+1
source

All Articles