swift - 在 SwiftUI 中为路径描边绘制动画

标签 swift swiftui

要为过去的路径设置动画,我可以执行以下操作:

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

        }
    }
}

最佳答案

它可以使用带有动画结束的 .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
            }

        //}
    }
}

关于swift - 在 SwiftUI 中为路径描边绘制动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60680233/

相关文章:

ios - 如何搜索经过身份验证的用户 Firebase iOS Swift

ios - SwiftUI VStack 右对齐单个元素

realm - SwiftUI 导航自动关闭/弹出 - Realm

ios - 嵌套的 CollectionView 不会在滑动时隐藏导航栏

iOS NSBundle 获取项目文件结构中组内的所有文件

swift - md5 可以返回无效结果吗?

SwiftUI 从数据中获取数据(contentsOf : file)

ios - iPhone 不可用。请重新连接设备。/iOS 14.2 - Xcode 12.1

ios - 如何在 SwiftUI 中将项目与 VStack 内的顶部对齐?

macos - 如何使用 Swift 1.2/Cocoa 以编程方式在 NSToolbar 上选择 NSToolbarItem