首页 > 解决方案 > 是否可以在 SwiftUI 中的某个路径上为视图设置动画

问题描述

是否可以在 SwiftUI 中的某个路径上为视图设置动画。在 SwiftUI 之前,它只是设置其层的路径属性的问题。我现在怎么做类似的事情?

编辑 这是一个例子,我是如何用 UIKit 做的

let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
    animation.duration = CFTimeInterval(duration)
    animation.repeatCount = 1
    animation.path = path.cgPath
    animation.isRemovedOnCompletion = true
    animation.fillMode = .forwards
    animation.timingFunction = CAMediaTimingFunction(name: .linear)

viewToAnimate.layer.add(animation, forKey: "someAnimationName")

标签: iosswiftxcodeswiftui

解决方案


对的,这是可能的。这是一个可能方法的演示(粗糙,许多参数只是硬编码,但可以通过属性、构造函数、回调等进行配置)

SwiftUI 关键帧动画

struct PathAnimatingView<Content>: UIViewRepresentable where Content: View {
    let path: Path
    let content: () -> Content

    func makeUIView(context: UIViewRepresentableContext<PathAnimatingView>) -> UIView {
        let view = UIView(frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.layer.borderColor = UIColor.red.cgColor
        view.layer.borderWidth = 2.0

        let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
            animation.duration = CFTimeInterval(3)
            animation.repeatCount = 3
            animation.path = path.cgPath
            animation.isRemovedOnCompletion = false
            animation.fillMode = .forwards
            animation.timingFunction = CAMediaTimingFunction(name: .linear)

        let sub = UIHostingController(rootView: content())
        sub.view.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(sub.view)
        sub.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        sub.view.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        view.layer.add(animation, forKey: "someAnimationName")
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PathAnimatingView>) {
    }

    typealias UIViewType = UIView
}

struct TestAnimationByPath: View {
    var body: some View {
        VStack {
            PathAnimatingView(path: Circle().path(in: 
                              CGRect(x: 100, y: 100, width: 100, height: 100))) {
                Text("Hello, World!")
            }
        }
    }
}

推荐阅读