How to Round Specific Corners Only with SwiftUI

The cornerRadius modifier clips a view to its bounding frame, with the specified corner radius. In another words, any SwiftUI view can have its corners rounded using the cornerRadius() modifier. But is there a way to round only specific corners such as the top? Of course! We will create a rectangle with a top-right rounded corner and a bottom-left rounded corner as below. Let’s do it step by step!

A red rectangle with a bottom left rounded corner and a top right corner.

First of all, we need to create a custom shape. SwiftUI draws custom shapes using a path that can contain lines. In this shape, we define two parameters which are radius and corners. In addition, we create a specific rounded corners path by UIBezierPath.

struct RoundedCorner: Shape {

    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

What is the path? Paths can define simple shapes such as rectangles, ovals, and arcs or define complex polygons that incorporate straight and curved line segments. After defining the shape, you can use additional methods of this class to render the path in the current drawing context.

Next, we create a custom modifier by creating a extension for the View structure as the below code.

extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape(RoundedCorner(radius: radius, corners: corners))
    }
}

This modifier also named cornerRadius, but it accepts an additional corners parameter to store the specific rounded corners.

SwiftUI also allows you clip any view to control its shape, all by using the clipShape() modifier. Use clipShape(_:style:) to clip the view to the provided shape. By applying a clipping shape to a view, you preserve the parts of the view covered by the shape, while eliminating other parts of the view. The clipping shape itself isn’t visible.

In this tutorial, the view will be clipped by the custom shape and return the clipped view as result.

Finally, create a red rectangle with a bottom left rounded corner and a top right corner as the below code.

Final result

Color.red
    .frame(width: 200, height: 300)
    .cornerRadius(30, corners: [.bottomLeft, .topRight])

Leave a Reply

Your email address will not be published. Required fields are marked *