How to display solid shapes in swiftUI?

By | October 6, 2024

Sometimes we need to display basic shapes in our apps just to get more attractive UI or just to highlight something. SwiftUI has several build in shapes to help the user to ease the development. It has several built-in shapes such as rectangles, circles, and capsules, each of which can be created, color, and positioned as needed.

For example, if you wanted a 300×300 orange rectangle, you would use this

    var body: some View {
        Rectangle()
            .fill(.orange)
            .frame(width: 300, height: 300)
    }

Similarly, if you wanted a 200×200 orange circle you would use this

    var body: some View {
        Circle()
            .fill(.orange)
            .frame(width: 300, height: 300)
    }

There’s a dedicated shape for rounded rectangles, allowing you to customize how much rounding should be applied, as well as having complete control over the type of rounding. For example, below code snippet creates a rounded rectangle with 30 points of rounding on each corner

    var body: some View {
        RoundedRectangle(cornerRadius: 25)
            .fill(.orange)
            .frame(width: 150, height: 100)
    }

Lastly, SwiftUI provides a Capsule() shape as a specialized form of rounded rectangles, where the shortest edge of the rectangle is always fully rounded. This is one of the most commonly used shapes in swiftUI. Mostly used with login buttons and other action buttons. This is a popular style with buttons, because you get a lozenge-shaped button in just a couple of lines of code.

    var body: some View {
        Capsule()
            .fill(.orange)
            .frame(width: 300, height: 100)
    }

Leave a Reply

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