ios - 是否可以在 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")
解决方案
对的,这是可能的。这是一个可能方法的演示(粗糙,许多参数只是硬编码,但可以通过属性、构造函数、回调等进行配置)
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!")
}
}
}
}
推荐阅读
- php - 未找到特征“Stripe/ApiOperations/Request”
- java - 即使我向其中添加元素,JComboBox 下拉列表仍为空
- reactjs - React 和 TypeScript 如何通过道具在 onClick 上将数据从子级传递给父级
- discord.js - 对消息 discord.js 的随机响应
- r - 这些袋装 ETS 模型的预测区间是否计算正确?(用 R 编码)
- machine-learning - 处理特征工程中的经纬度
- firebase - 如何在 Unity 中超时 Firebase 任务
- python - Django 从 url 取值
- python - 使用 sha512_crypt 解密密码 - python3
- symmetricds - 初始加载在 sym_x 表模式中创建我的表