4

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?

David Matos
  • 560
  • 2
  • 11
  • 24
  • The best option in my option would be to override the onDraw of your view and use drawPath for example where the path is a rounded rect. – Pedro Oliveira Nov 24 '15 at 11:59

3 Answers3

6

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

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129
2

Try to use

RectF r = new RectF(10,100,200,400);
canvas.drawRoundRect(r, 0, 0, mPaint);

about or square case of it.

The other approach is to use clipping mask. The concept of this idea is to use PorterDuffXfermode or PorterDuff . This is an example for the rounded corner view. I don't know what directly you want that's why I just can give to base methods I've used. The other example.

Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

Try this:

val circlePath = Path().apply {
        addCircle(x, y, radius, Path.Direction.CW)
    }
canvas.clipPath(circlePath)
Mattia Ferigutti
  • 2,608
  • 1
  • 18
  • 22