Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Custom Shape to a View in SwiftUI
Written by Team Kodeco

Have you ever wanted to use a unique shape for your SwiftUI views? With SwiftUI, it’s possible to create and use custom shapes for your views. In this cookbook entry, you’ll learn how to add a custom shape to a view in SwiftUI.

To create a custom shape, you must create a new struct that conforms to the Shape protocol. The Shape protocol requires that you implement a single method: path(in rect: CGRect) -> Path. The path method should return a Path object that defines the shape.

Here’s an example of how to create a custom shape:

struct DiamondShape: Shape {
  func path(in rect: CGRect) -> Path {
    var path = Path()
    let center = CGPoint(x: rect.width / 2, y: rect.height / 2)

    path.move(to: CGPoint(x: center.x, y: 0))
    path.addLine(to: CGPoint(x: rect.width, y: center.y))
    path.addLine(to: CGPoint(x: center.x, y: rect.height))
    path.addLine(to: CGPoint(x: 0, y: center.y))
    path.addLine(to: CGPoint(x: center.x, y: 0))

    return path
  }
}

In this example, we’re creating a DiamondShape struct that conforms to the Shape protocol. In the path method, you define a series of points and lines to draw a diamond.

Once you’ve created your custom shape, you can use it in any view by calling the .fill() or .stroke() modifier on the view, passing in your custom shape as an argument. Here’s an example of how to use the DiamondShape in a view:

struct ContentView: View {
  var body: some View {
    DiamondShape()
      .fill(Color.red)
      .frame(width: 200, height: 200)
  }
}

The preview for this view should now look as follows:

An example of a custom shape in SwiftUI.
An example of a custom shape in SwiftUI.

In this example, we’re creating a DiamondViewthat uses the custom DiamondShape and sets the fill color to red. We’re also giving the view a fixed width and height of 200 points.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.