Is it possible to mask views? For example, if I have a design that calls for a List View to be visible within an oval shaped opening. Is there a way to create a mask for a view? Is it called something else? Because all the references I find to masking in the android docs are talking about masking a canvas object or drawable. But I don't think making a drawable of an interactive object like a list View would be a good approach. Is this just a limitation to deal with for now?
Asked
Active
Viewed 3.0k times
2 Answers
39
Yes, it is - you have to override the drawing method of your view - i.e:
......
final Path path = new Path();
path.addRoundRect(new RectF(0,0,getWidth(),getHeight()),10,10,Direction.CW);
......
@Override
protected void dispatchDraw(Canvas canvas){
canvas.clipPath(path);
super.dispatchDraw(canvas);
}
this will draw your view only in the boundaries set by path.

asenovm
- 6,397
- 2
- 41
- 52
-
1You could also create whatever "mask" effect you want and just put it into its own View and put it ontop / in front of the view in question. If you just need this effect for 1 specific view this would save you the trouble of creating your own views and editing the draw methods. – FoamyGuy Sep 26 '11 at 18:05
-
That would be plain wrong, Tim. You'll slower your app by creating a completely unnecessary view hierarchy on a mobile platform where performance is crucial. – asenovm Sep 26 '11 at 18:08
-
I agree that it would result in worse performance. I contend that if he is applying it to 1 view inside 1 activity the difference in performance will be unnoticeable to the human eye on the devices that are out there. And that doing it with separate views may seem less daunting to some people than trying create their own view so that they can override the draw methods. I know doing things like that becomes trivial after you've gotten a few under your belt. But if you have never done that before, to me seems like it could be a bit daunting. – FoamyGuy Sep 26 '11 at 18:29
-
If I overwrite the dispatchDraw Method of my imageview with this nothing happens. The image is drawn as before. – Janusz Feb 10 '12 at 08:02
-
That would be because the ImageView is not a ViewGroup. You need to override the `onDraw` method by using the same code as above and it will work. – asenovm Feb 10 '12 at 19:59
-
6This solution is not viable for masking views that are animated – Tommy Sadiq Hinrichsen Jul 02 '15 at 13:29
14
Yes, you can even mask complete layouts. Shameless selfplug
<com.christophesmet.android.views.maskableframelayout.MaskableFrameLayout
android:id="@+id/frm_mask_animated"
android:layout_width="100dp"
app:porterduffxfermode="DST_IN"
app:mask="@drawable/animation_mask"
android:layout_height="100dp">
<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/unicorn"/>
You can find it here

Christophe Smet
- 850
- 10
- 11