要使过去的路径具有动画效果,我可以这样做:
let pathLayer = CAShapeLayer()
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathLayer.path = path.cgPath
pathAnimation.duration = 0.3
pathAnimation.fromValue = 0
pathAnimation.toValue = 1
pathLayer.add(pathAnimation, forKey: "strokeEnd")在使用SwiftUI时,我看不到使用CABasicAnimation的方法。如何使用SwiftUI动画绘制以下路径?
struct AnimationView: View {
var body: some View {
GeometryReader { geo in
MyLines(height: geo.size.height, width: geo.size.width)
}
}
}
struct MyLines: View {
var height: CGFloat
var width: CGFloat
var body: some View {
ZStack {
Path { path in
path.move(to: CGPoint(x: 0, y: height/2))
path.addLine(to: CGPoint(x: width/2, y: height))
path.addLine(to: CGPoint(x: width, y: 0))
}
.stroke(Color.black, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
}
}
}发布于 2020-03-14 14:47:49
它可以与动画结尾一起使用.trim,就像下面修改的代码一样
struct MyLines: View {
var height: CGFloat
var width: CGFloat
@State private var percentage: CGFloat = .zero
var body: some View {
// ZStack { // as for me, looks better w/o stack which tighten path
Path { path in
path.move(to: CGPoint(x: 0, y: height/2))
path.addLine(to: CGPoint(x: width/2, y: height))
path.addLine(to: CGPoint(x: width, y: 0))
}
.trim(from: 0, to: percentage) // << breaks path by parts, animatable
.stroke(Color.black, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
.animation(.easeOut(duration: 2.0)) // << animate
.onAppear {
self.percentage = 1.0 // << activates animation for 0 to the end
}
//}
}
}https://stackoverflow.com/questions/60680233
复制相似问题