I have a mask bitmap with a half is red color and ones is transparent like this https://www.dropbox.com/s/931ixef6myzusi0/s_2.png
I want to use mask bitmap to draw content on canvas only visible in red area, code like this:
Paint paint = new Paint();
public void draw(Canvas canvas) {
// draw content here
...
//and mask bitmap here
paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
canvas.drawBitmap(maskBitmap, 0, 0, paint);
}
The result as my expecting (content only visible in red area, BUT THE TRANSPARENT AREA BECOME BLACK IS PROBLEM!)
this image result :https://www.dropbox.com/s/mqj48992wllfkiq/s_2%20copy.png Anyone help me???
I encountered the same problem in my custom view and instead of decoding the bitmap from a resource, I had created the original bitmap and the masking bitmap from the scratch via
canvas.draw*()
methods (since both the original and mask are basic shapes). I was getting theblank opaque space
instead of atransparent
one. I fixed it by setting a hardware layer to my view.More info on why this is to be done here: https://stackoverflow.com/a/33483016/4747587
Here is a solution which helped me to implement masking:
The mask should be a white image with transparency.
It will work like this:
+ =
I like the approach from Er. Praful Parmar's answer but for me it did not quite work as expected. I had problems, because some scaling was going on without intention.
My Bitmaps had a different density than my device and this messed things up.
Also I wanted to reduce the creation of Objects, so I moved the
Paint
object to a constant for reuse.So here is my utils method: