FREE: Start my 100 Days of SwiftUI today! >>

How to draw part of a solid shape using trim()

Paul Hudson    @twostraws   

Fully updated for Xcode 11.5

SwiftUI lets us draw only part of a stroke or fill for a shape using its trim() modifier, which takes two parameters: a start value and an end value, both stored as a CGFloat between 0 and 1.

For example, if you wanted a semicircle you would write this:

Circle()
    .trim(from: 0, to: 0.5)
    .frame(width: 200, height: 200)

SwiftUI draws its shapes so that 0 degrees is directly to the right, so if you want to change that so 0 degrees is directly up you should apply a rotationEffect() modifier.

For example, this uses a timer to adjust the values being passed into trim() so that a circle’s stroke grows over time, like a progress indicator:

struct ContentView: View {
    @State private var completionAmount: CGFloat = 0.0
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Rectangle()
            .trim(from: 0, to: completionAmount)
            .stroke(Color.red, lineWidth: 20)
            .frame(width: 200, height: 200)
            .rotationEffect(.degrees(-90))
            .onReceive(timer) { _ in
                withAnimation {
                    guard self.completionAmount < 1 else { return }
                    self.completionAmount += 0.2
                }
            }
    }
}

You can also use trim() with filled shapes, although the result is a little odd when animated.

Hacking with Swift is sponsored by Bitrise

SPONSORED Build better iOS apps, faster. Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS-specific solutions.

Sign up for a free trial!

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

Support my work on Patreon

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!