FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

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

Paul Hudson    @twostraws   

Updated for Xcode 13.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)

Download this as an Xcode project

The bottom half of a circle.

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 rectangle’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 {
                    if completionAmount == 1 { 
                        completionAmount = 0
                    } else {
                        completionAmount += 0.2
                    }
                }
            }
    }
}

Download this as an Xcode project

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

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn 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.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.