简体   繁体   English

是否可以在 SwiftUI 中的特定路径上为视图设置动画

[英]Is it possible to animate view on a certain Path in SwiftUI

Is it possible to animate view on a certain Path in SwiftUI.是否可以在 SwiftUI 中为特定路径上的视图设置动画。 Previous to SwiftUI it was just a matter of setting path property of its layer.在 SwiftUI 之前,它只是设置其图层的路径属性的问题。 How can I do something similar now?我现在怎么做类似的事情?

EDIT Here is an example how i did it with UIKit编辑这是我如何用 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")

Yes, it is possible.对的,这是可能的。 Here is a demo of possible approach (scratchy, many parameters just hardcoded, but the could be configured via properties, constructor, callbacks, etc.)这是一个可能的方法的演示(粗糙,许多参数只是硬编码,但可以通过属性、构造函数、回调等进行配置)

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!")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM