Narendra Kothamire
Narendra Kothamire

Reputation: 973

How to do masking in android to get this effect?

http://www.flashfridge.com/tutorial.asp?ID=135

I want similar masking effect in android. I want to move a blurred oval as user moves his finger and I want that oval to mask underlying bitmap so that i can see only that portion of bitmap, but do not know how to get this effect in android.

Upvotes: 1

Views: 846

Answers (1)

Kasra
Kasra

Reputation: 3145

You can use PorterDuff.Mode.DST_IN to achieve this:

public static Bitmap getMaskedBitmap(Resources res, int sourceResId, int maskResId) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    options.inMutable = true;
  }
  options.inPreferredConfig = Bitmap.Config.ARGB_8888;
  Bitmap source = BitmapFactory.decodeResource(res, sourceResId, options);
  Bitmap bitmap;
  if (source.isMutable()) {
    bitmap = source;
  } else {
    bitmap = source.copy(Bitmap.Config.ARGB_8888, true);
    source.recycle();
  }
  bitmap.setHasAlpha(true);
  Canvas canvas = new Canvas(bitmap);
  Bitmap mask = BitmapFactory.decodeResource(res, maskResId);
  Paint paint = new Paint();
  paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
  canvas.drawBitmap(mask, 0, 0, paint);
  mask.recycle();
  return bitmap;
}

Full tutorial here.

Upvotes: 1

Related Questions