user868395
user868395

Reputation: 47

How to cut one bitmap from other bitmap

I need to cut Bitmap1 from Bitmap2.. For example, i have Bitmap1 (decode from Resources drawable) and Bitmap2 (decode from Resources drawable too).

Bitmap1:

|   |
 > <
|   |

Bitmap2:

|xxx|
|xxx|
|xxx|

I need result:

|xxx|
 >x<
|xxx|

Can somebody give me sample code?

Android.

Upvotes: 1

Views: 422

Answers (1)

Jens
Jens

Reputation: 17077

You could load both bitmaps and use PorterDuffXfermode and DST_IN to mask "Bitmap2", sort of like this:

Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap2);
Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap1);
Bitmap bitmap2MaskedByBitmap1 = Bitmap.createBitmap(bitmap2.getWidth(), bitmap2.getHeight(), bitmap2.getConfig());
Canvas canvas = new Canvas(bitmap2MaskedByBitmap1);

Paint paint = new Paint();
paint.setFilterBitmap(false);

canvas.drawBitmap(bitmap2, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawBitmap(bitmap1, 0, 0, paint);
bitmap2.recycle();
bitmap1.recycle();

// bitmap2MaskedByBitmap1 should now contain the desired image
// as long as your Bitmap1 mask isn't sh-t.

Upvotes: 3

Related Questions