How to draw part of a solid shape using trim()
About 2 min
How to draw part of a solid shape using trim() 관련
SwiftUI by Example
Back to Home
How to draw part of a solid shape using trim() | SwiftUI by Example
How to draw part of a solid shape using trim()
Updated for Xcode 15
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)
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
}
}
}
}
}
You can also use trim()
with filled shapes, although the result is a little weird when animated.
Similar solutions…
How to display solid shapes | SwiftUI by Example
How to display solid shapes
How to clip a view so only part is visible | SwiftUI by Example
How to clip a view so only part is visible
How to draw a custom path | SwiftUI by Example
How to draw a custom path
How to draw a shadow around a view | SwiftUI by Example
How to draw a shadow around a view
How to draw images using Image views | SwiftUI by Example
How to draw images using Image views