Henrique
Henrique

Reputation: 5011

How to mask only certain parts of a bitmap in Android

I want to be able to use the following image to mask other bitmap. So basically, I'm trying to get the mask image and replace it's black content with another bitmap. Like this for example:

This is the mask This is the final result

I'm able to use this mask and create a round version of the original bitmap, but that does not retain that orange border around it. Any thoughts on how I can accomplish this effect? Thanks.

The code that I am using (that only creates a round image) is the following:

private static Bitmap applyMask(ImageView imageView, Bitmap mainImage) {
    Canvas canvas = new Canvas();

    Bitmap result result = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);            

    canvas.setBitmap(result);
    Paint paint = new Paint();

    // resize image fills the whole canvas
    canvas.drawBitmap(mainImage, null, new Rect(0,  0, 50, 50), paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    canvas.drawBitmap(sMaskImage, 0, 0, paint);
    paint.setXfermode(null);

    return result;
}

Upvotes: 0

Views: 2658

Answers (1)

yahya
yahya

Reputation: 4860

I use below code snipped to set masked images, this sample "bm" is my bitmap and "mMaskSource" is the resource id of mask object position in my drawable folder.

Bitmap mask = BitmapFactory.decodeResource(getResources(), mMaskSource);
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),
            Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
bm = Bitmap.createScaledBitmap(bm, mask.getWidth(), mask.getHeight(),
            true);
mCanvas.drawBitmap(bm, 0, 0, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);

And finally you can use "result" bitmap object however you wish.

Upvotes: 1

Related Questions