NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to draw a custom path

Paul Hudson    @twostraws   

Updated for Xcode 12.0

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 CGPathorUIBezierPath`, then convert the result to a SwiftUI path.

Note: The code below uses SwiftUI’s native path drawing API, but this is broken in beta 5 – your code will compile but crash at runtime. Apple has said this ought to be fixed in beta 6.

If you want to use SwiftUI’s native Path type, create a variable instance of it then add as many points 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 rotated squares with something like this:

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

        let rotations = 5
        let amount = .pi / CGFloat(rotations)
        let transform = CGAffineTransform(rotationAngle: amount)

        for _ in 0 ..< rotations {
            path = path.applying(transform)

            path.addRect(CGRect(x: -rect.width / 2, y: -rect.height / 2, width: rect.width, height: rect.height))
        }

        return path
    }
}

You could then use it inside a view like this:

struct ContentView: View {
    var body: some View {
        SpiroSquare()
            .stroke()
            .frame(width: 200, height: 200)
    }
}
Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

Link copied to your pasteboard.