在SwiftUI中实现路径描边动画绘制

7

过去,要对一条路径进行动画处理,我可以这样做:

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))

        }
    }
}
1个回答

24

重新测试:Xcode 13.4 / iOS 15.5

在此输入图像描述

可以使用带有可动画结束的.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), value: percentage) // << animate
            .onAppear {
                self.percentage = 1.0 // << activates animation for 0 to the end
            }

        //}
    }
}

1
这太棒了,感谢Asperi提供又一个好答案。我能够使用.trim、.animation和.onAppear的组合以及@State变量来动画绘制一个圆。您可以调整持续时间来改变绘制速度。在Swift 5中,这非常有效。 - FontFamily

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接