Skip to main content

How to draw a custom path

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to draw a custom path 관련

SwiftUI by Example

Back to Home

How to draw a custom path | SwiftUI by Example

How to draw a custom path

Updated for Xcode 15

SwiftUI lets us draw custom paths by conforming to the Shape protocol, so we can create our own shapes that work the same as Rectangle, Capsule, and Circle. Conforming to this protocol isn’t hard, because all you need to do is support a path(in:) method that accepts a CGRect and returns a Path. Even better, you can use any paths you’ve previously built using CGPath or UIBezierPath, then convert the result to a SwiftUI path.

If you want to use SwiftUI’s native Path type, create a variable instance of it then add as many points or shapes as you need. Don’t think about colors, fills, or stroke widths – you’re focusing on the raw shape here, and those kinds of settings are provided when your custom path is used.

For example, we could make a creative effect by drawing a series of shrinking squares, then placing that shape into a SwiftUI view with a stroke and a size:

struct ShrinkingSquares: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()

        for i in stride(from: 1, through: 100, by: 5.0) {
            let rect = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
            let insetRect = rect.insetBy(dx: i, dy: i)
            path.addRect(insetRect)
        }

        return path
    }
}

struct ContentView: View {
    var body: some View {
        ShrinkingSquares()
            .stroke()
            .frame(width: 200, height: 200)
    }
}

Download this as an Xcode projectopen in new window

A series of concentric square outlines creating an optical illusion.
A series of concentric square outlines creating an optical illusion.
Similar solutions…
How to draw polygons and stars | SwiftUI by Example

How to draw polygons and stars
How to draw a checkerboard | SwiftUI by Example

How to draw a checkerboard
How to draw a border inside a view | SwiftUI by Example

How to draw a border inside a view
How to draw a shadow around a view | SwiftUI by Example

How to draw a shadow around a view
How to draw a border around a view | SwiftUI by Example

How to draw a border around a view

이찬희 (MarkiiimarK)
Never Stop Learning.