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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.