在 SwiftUI 中为路径描边绘制动画 [英] animate path stroke drawing in SwiftUI

查看:36
本文介绍了在 SwiftUI 中为路径描边绘制动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要为过去的路径设置动画,我可以这样做:

To animate a path in the past I could do something like this:

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 为以下路径的绘图设置动画?

Using SwiftUI, I don't see a way to use CABasicAnimation. How would I animate the drawing of the following path, using 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 与动画结束,就像下面你修改的代码

It can be used .trim with animatable end, like below with your modified code

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
            }

        //}
    }
}

这篇关于在 SwiftUI 中为路径描边绘制动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆