Creating Shapes in SwiftUI
Last updated
Last updated
SwiftUI provides a robust set of tools for creating and customizing shapes in your app. Shapes like Circles
, Ellipse
, Rectangle
, Capsule
, and RoundedRectangle
can be easily added to your views, making it simple to create visually appealing designs. This guide will walk you through the basics of adding these shapes and customizing their appearance.
The Circle
shape is straightforward to create and use. Here's an example:
In this example, we create a Circle
shape and set its frame to 200x200 points.
The Ellipse
shape can be created similarly, and it automatically adjusts its aspect ratio based on the frame provided:
This code snippet creates an ellipse with a width of 300 points and a height of 200 points.
Creating a rectangle is just as simple:
Here, a Rectangle
shape is created with specified dimensions.
A RoundedRectangle
shape allows you to set the corner radius for rounded corners:
This creates a rectangle with rounded corners, where the corner radius is set to 30 points.
Shapes in SwiftUI can be customized with various modifiers to change their appearance.
You can fill a shape with a color or add a stroke (border):
The first example fills the circle with red, and the second adds a red stroke to the rectangle.
You can adjust the opacity and add a shadow to shapes:
This example creates an ellipse with blue fill, and a shadow.
SwiftUI also supports gradient fills for shapes:
Here, we apply a linear gradient to a rounded rectangle.