Search code examples
iosswiftuibezierpath

Round corners with different radius


I need to round top corners of a view with any value and also bottom corners of the same view with a different value. Here, I have the code I thought it would solve this. But it doesn't work... Any idea?

        bottomPath = UIBezierPath(roundedRect:self.bounds,
                               byRoundingCorners:[.bottomLeft, .bottomRight],
                               cornerRadii: CGSize(width: radius, height:  radius))
        topPath = UIBezierPath(roundedRect:self.bounds,
                               byRoundingCorners:[.topLeft, .topRight],
                               cornerRadii: CGSize(width: radius, height:  radius))

        bottomPath.append(topPath)
        maskLayer = CAShapeLayer()
        maskLayer?.path = bottomPath.cgPath
        self.layer.mask = maskLayer

If I comment bottomPath or topPath I get top or bottom corners rounded, but never both of them Thank you


Solution

  • I don't believe there is any system call to create a rounded rectangle with different corner radii for each corner. The function UIBezierPath(roundedRect:byRoundingCorners:cornerRadii:) that you are using will create a rounded rectangle with some corners rounded and some not, but the corners you ask to round will all have the same radius.

    If you want to create a path with different corners rounded to different radii I'm pretty sure you'll have to build such a path yourself using arcs for each corner and line segments for the flat sides of the rounded rectangle. (You'd draw a closed path composed of an arc with an angle of ∏/2, then a line segment, and repeat that 4 times. The center of each arc would be that corner of the rectangle, inset by the corner radius in both dimensions. It helps to diagram it out on graph paper.)

    EDIT:

    With a little digging I found this post that includes code to generate a rounded rect with a different corner radius for each corner:

    IOS: Is possible to rounder radius with different value in each corner