NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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

Paul Hudson    @twostraws   

Updated for Xcode 12.0

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.

Subscribe to Hacking with Swift+

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.0/5

Link copied to your pasteboard.