This is my solution to the arrow challenge, and its animation.
The arrow shape is easy in itself, but when I stroked it went outside its bounds. So I needed .strokeBorder()
and for that I made the ArrowView
struct Insettable
via a var
insetAmount
. This makes the arrow slightly smaller when I increase the lineWidth
of the stroke (in my main struct, DrawingView
).
Next challenge was to animate the change of lineWidth
. I put this under withAnimation
, and this indeed animates the change of lineWidth
. But the change of the arrow size, governed by insetAmount
, was still sudden. So I put insetAmount
under animatableData
.
The difficulty for me was to realize that lineWidth
and insetAmount
both need to be animated, and that this must be done in different manners.
This solution does not look too complicated, but I would be interested in any possible improvements or alternatives.
import SwiftUI
struct Arrow: InsettableShape {
var insetAmount = 0.0
var animatableData: Double {
get { insetAmount }
set { insetAmount = newValue}
}
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.height - insetAmount))
path.addLine(to: CGPoint(x: rect.midX, y: insetAmount))
path.addLine(to: CGPoint(x: insetAmount, y: rect.height * 0.33))
path.move(to: CGPoint(x: rect.midX, y: insetAmount))
path.addLine(to: CGPoint(x: rect.width - insetAmount, y: rect.height * 0.33))
return path
}
func inset(by amount: CGFloat) -> some InsettableShape {
var arrow = self
arrow.insetAmount += amount
return arrow
}
}
struct DrawingView: View {
@State private var lineWidth = 1.0
var body: some View {
VStack {
Arrow()
.strokeBorder(.blue, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round))
Spacer()
Button("Change line width") {
withAnimation(.easeInOut(duration: 1)) {
lineWidth = Double.random(in: 1...20)
}
}
}
}
}