Mastering Shapes in SwiftUI: Circles, Ellipses, Capsules, Rectangles, and Rounded Rectangles

In this tutorial, you'll learn how to use different shapes such as circle, ellipse, capsule, rectangle and rounded rectangle in SwiftUI to add visual interest to your app's user interface. You'll see how to create these shapes and customize their appearance using properties such as fill color, stroke color, stroke style, and more. You'll also learn how to combine multiple shapes and add them to a view hierarchy to create more complex shapes. By the end of this tutorial, you'll be able to create custom shapes that fit your design needs and make your SwiftUI app stand out.

How to use shapes like circle, ellipse, capsule, rectangle and rounded rectangle

With SwiftUI, you get access to five built-in shapes which are circle, ellipse, rectangle, rounded rectangle and capsule.

Shapes vs Stacks 

Unlike stacks, shapes take the maximum space. 

To color them, you use fill and foregroundColor instead of background. They're great for clipping content and setting a border style.


Circle 

The Circle allows you to draw a perfect circular shape. The circular shape will have a diameter that's equal to the smaller number between width and height.

  Circle()
            .stroke(Color.black, lineWidth: 2)
            .frame(width: 44, height: 44)

..

Ellipse 

The Ellipse is like a circle, but without the perfect aspect ratio 1:1. When the width and height are different, it'll fill the space and distort itself.

Ellipse()
	.stroke(Color.black, lineWidth: 2)
	.frame(width: 44, height: 88)

..

Rectangle 

While most elements in SwiftUI such as stacks, colors, gradients start as rectangles, they're not shapes. The Rectangle has a shape property, allowing it to have a stroke or serve as a mask.

Rectangle()
            .foregroundColor(.blue)
            .ignoresSafeArea()

..

RoundedRectangle 

The RoundedRectangle comes with useful cornerRadius and style properties. It's great for creating buttons and generating the smooth corners of iOS.

 RoundedRectangle(cornerRadius: 30, style: .continuous)
            .fill(Color.green)
            .frame(height: 44)
            .overlay(Text("Submit").bold())

..

Capsule 

Similar to the RoundedRectangle, the Capsule is pill-shaped. Each end of of the capsule is made of a half-circle. You can use them for buttons.

 Capsule()
            .fill(Color.green)
            .frame(height: 44)
            .overlay(Text("Submit").bold())

..

Final Layout 

In the final layout, you can see that shapes are fantastic for clipping the content of a stack. On top of that, you can use them to set a border, use the maximum space and create really nice buttons.



Comments