ANDROID: Alpha Masking

Lets say we had 2 bg images, and wanted to use an alpha mask (black = invisible pixels, transparent = visible pixels) to mask those 2 bg images composite together...


(1) create default paint
(2) set filter bitmap to false
(3) draw bg #1
(4) draw bg #2
(5) set paint's setXfermode to dstOut
(6) draw mask
(7) set paint's setXfermode to null

however, if you are putting this View object on top of another view, the mask will ALSO mask out the pixels in the PARENT VIEW... this is obviously not wanted behavior. to resolve this, you could simply render everything to a mutable-bitmap, and in onDraw, just draw that bitmap instead. See below:


inside public void onDraw(Canvas onDrawCanvas);

mutable = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(mutable);
paint = new Paint();
paint.setFilterBitmap(false);

canvas.drawBitmap(bg1, 0, 0, paint);
canvas.drawBitmap(bg2, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);

onDrawCanvas.drawBitmap(bitmap, 0, 0, paint);

3 comments:

ProjectJourneyman said...

Thanks for the writeup - your example was the cleanest I could find showing how to write the masked image into a bitmap, and I got it working now.

Noé Rodríguez said...

What is the variable "mask"?

moshrabbi121 said...

The next time I read a weblog, I hope that it doesnt disappoint me as much as this one. I mean, I do know it was my choice to read, however I really thought youd have something interesting to say. All I hear is a bunch of whining about something that you might repair should you werent too busy on the lookout for attention. free online casino slots