AntonijoDev
AntonijoDev

Reputation: 1315

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

Is it possible to animate view on a certain Path in SwiftUI. Previous to SwiftUI it was just a matter of setting path property of its layer. How can I do something similar now?

EDIT Here is an example how i did it with 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")

Upvotes: 2

Views: 1756

Answers (1)

Asperi
Asperi

Reputation: 257937

Here is a demo of possible approach (just a sketch: many parameters just hardcoded, but they could be configured via properties, constructor, callbacks, etc.)

SwiftUI KeyframeAnimation

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

Upvotes: 4

Related Questions