0

Is there any way in Android (from API 15) to clip/subtract views like masking in photoshop?

See the example below: https://s31.postimg.org/d18lktjq3/index.jpg

The Red view is just a bold funny V shape, while the blue one is something more complex. Note that in the red view, the striped part is transparent. The result view i would like to obtain, is something like the blue big view, with the V shape of the second view, and anything above cut away.

Note that, in the final result, the space "inside" the V shape must be transparent.

Currently i achieve this effect using the two views one on top of the other (filling the gap in the V shape view), but this is not optimal because i have to know exactly what the other view is, and the summed up view is bigger than the source.

Thank you

1 Answers1

1

In Android, this is done using Porter-Duff Transfer Modes.

Your best best for this is to have two overlay bitmaps: One that has the red V-shape, and a complementary bitmap that represents everything you want to cut out of the lower layer.

With a custom view, you override onDraw() to do these steps:

  • Draw the base (blue) bitmap
  • Draw the red stripe using Porter-Duff mode SRC_OVER
  • Draw the top V cutout using Porter-Duff mode CLEAR

Code would look something like this (assuming you have created the bitmaps and computed the x,y coordinates where you want to draw them):

    Paint paint = new Paint();
    paint.setAntiAlias(true);

    canvas.drawBitmap(blue_base, blueX, blueY, paint); 

    // draw the red v on top of the blue part
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
    canvas.drawBitmap(red_v, redX, redY, paint);

    // erase the unwanted pixels from the blue part
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    canvas.drawBitmap(cut_out, redX, redY, paint);

Here's an interesting tutorial to get you started: Punch a hole in a bitmap by using Android's porter-duff Xfer - TechRepublic

kris larson
  • 30,387
  • 5
  • 62
  • 74