Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I clip a view with a circle using setClipBounds?

Tags:

android

I have the following code to delimit the area of a view to be drawn:

Rect rect = new Rect();
rect.set(0, 0, 100, 100);
View.setClipBounds(rect);

This will draw my view only on the specified rectangle (or square, in this case). However, I wanted the view to be clipped to a circle. Is there any way to somehow round the corners of a Rect object?

like image 943
David Matos Avatar asked Feb 08 '23 11:02

David Matos


1 Answers

In this case, you've to subclass that view and add some extra logic to it.

Add these codes to its constructor method, or wherever you would like to initialize the view.

final Path path = new Path();
path.addRoundRect(new RectF(0,0,getWidth(),getHeight()),10,10,Direction.CW);

Using these codes, you're defining a path along which your view is going to be drawn (the area inside the boundaries of the patch).

Add this method to the class to apply this mask on your view.

@Override
protected void dispatchDraw(Canvas canvas){
    canvas.clipPath(path);
    super.dispatchDraw(canvas);
}

Credits: https://stackoverflow.com/a/7559233/1841194

like image 78
frogatto Avatar answered Feb 11 '23 00:02

frogatto