Alpha Compositing Tutorial with Britney Spears and Guillermo Diaz


britney

I was attempting to use PorterDuff.Mode.DST_IN to apply a rounded rectangle to images. The mask was successful in removing the parts of the image I did not want. However it was leaving behind solid black instead of transparent. This is not what I wanted.

britneyandguillermobad

After researching the problem for a while I discovered that I needed create an additional layer and bitmap to get rid of the black color left over. While I was at it I decided to write a tutorial about it. My example uses paths to create a star mask. I just saw this music video and decided to make my post a bit different. Would you hold it against me? 😉



guillermo1. Create a Bitmap that will be Masked. In my case I selected a picture of Guillermo Diaz.

Bitmap lImageToMask = BitmapFactory.decodeResource(getResources(), R.drawable.guillermo);
2. Create a paint object.
3. Create a Bitmap for our Canvas Mask.
//Bitmap that the canvas will write to
Bitmap lImageMask = Bitmap.createBitmap(
mDesiredSize,
mDesiredSize,
Bitmap.Config.ARGB_8888);// Note that ARGB_8888 is important for getting alpha transparencies

5. Assign the Bitmap to the Canvas, and do our other operations for the mask(in my case I added a star shaped path)
Canvas lImageMaskCanvas = new Canvas(lImageMask);

6.We set the Xfermode of the paint object with the appropriate PorterDuff.Mode

lDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

7. We then apply the Bitmap we wanted masked to the canvas(the one we created in step 5)

lImageMaskCanvas.drawBitmap(lImageMask, 0, 0, lDrawPaint);

Sweet! You now have the masked bitmap(lImageMask).
Optional assign a cool image to your background so that there is something behind the cutout.

That’s it! Code is complete. Enjoy!