Updated for Xcode 14.2
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 number 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
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 = 0.0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
Rectangle()
.trim(from: 0, to: completionAmount)
.stroke(.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.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.