With SwiftUI, you get access to five built-in shapes which are circle, ellipse, rectangle, rounded rectangle and capsule.
Downloads
To follow this tutorial, you can download the source file, which will help you compare your progress.
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("Sign up").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("Sign up").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.
ZStack {
Rectangle()
.fill(Color.blue).ignoresSafeArea()
VStack {
Circle()
.stroke(Color.black, lineWidth: 2)
.frame(width: 44, height: 44)
Text("Meng To").bold()
Capsule()
.foregroundColor(Color.green)
.frame(height: 44)
.overlay(Text("Sign up"))
}
.padding()
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 25.0, style: .continuous))
.padding()
}