5

So I'm fundamentally not understanding something about PorterDuff and its various modes. I have two images I am trying to combine, one being an aerial image and the other being an alpha mask meant to be overlayed on the aerial so only certain sections show through. I have a system currently where I can correctly overlay the mask onto the other image where only it comes through, but the problem is that in this case I have to have a background color and I need it to be transparent. (similar to the problem here Efficient Bitmap masking with black and white alpha mask in Android)

Bitmap thumbnail = Bitmap.createBitmap(mThumbnailSize, mThumbnailSize, Config.ARGB_8888);
Canvas canvas = new Canvas(thumbnail);

Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(aerial, transformation, paint);

paint = new Paint();
paint.setFilterBitmap(true);
paint.setColorFilter(new PorterDuffColorFilter(Color.WHITE,PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(overlay, transformation, paint);

I feel like I've tried every combination of ColorFilter, XferMode, even drawing the images in the reverse order but nothing seems to work. I feel like I am just completely misunderstanding how the PorterDuff modes work (basing a lot of my information on http://ssp.impulsetrain.com/porterduff.html).

If anyone has any insight on how to accomplish this, insight on what PorterDuff Mode I should use, whether I should be using an ColorFilter or XferMode, anything at all I would really appreciate it.

Thanks in advance

Community
  • 1
  • 1
StackJP
  • 1,450
  • 2
  • 16
  • 32

1 Answers1

0

May be I'm late but the solution is to make the background transparent so you get the alpha mask that you already know how to use. Here is a CSharp helper method to convert B/W image to the alpha mask.

private static Bitmap ConvertToAlphaMask(Bitmap mask)
{
        float[] src = {
                    0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0,
                    0.3f, 0.59f, 0.11f, 0, 0,
                    };

    var colorMatrix = new ColorMatrix(src);
    var filter = new ColorMatrixColorFilter(colorMatrix);
    var maskPaint = new Paint();
    maskPaint.SetColorFilter(filter);

    var alphaMask = Bitmap.CreateBitmap(mask.Width, mask.Height, Bitmap.Config.Argb8888);
    var canvas = new Canvas(alphaMask);
    canvas.DrawBitmap(mask, 0, 0, maskPaint);

    return alphaMask;
}
zavolokas
  • 697
  • 1
  • 5
  • 20