ios - 是否可以在 SwiftUI 中对某个路径上的 View 进行动画处理

标签 ios swift xcode swiftui

是否可以在 SwiftUI 中对某个路径上的 View 进行动画处理。在 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")

最佳答案

这里是一个可能方法的演示(只是一个草图:许多参数只是硬编码的,但它们可以通过属性、构造函数、回调等进行配置)

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

关于ios - 是否可以在 SwiftUI 中对某个路径上的 View 进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59648676/

相关文章:

iphone - 验证 iphone 是否已连接到基座

按下弹出 View Controller 时,iOS 11 导航栏大标题为黑色

iphone - 关于在iphone中从paypal获取交易ID

swift - Swift 编程语言第 37 页 : func works in code but not as method of a struct

ios - self.view setNeedsDisplay 和 self.view setNeedsLayout 不起作用

iOS 提取证书身份 : EXC_BAD_ACCESS

ios - 无需 Segue 即可传递标签

ios - 将依赖注入(inject)与 iOS 框架类的协议(protocol)结合使用

ios - Xcode PDFKit 表单自动计算

表格 View 中的 Swift Uicollectionview