OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在先前转换的 UIView 上正确地为转换设置动画 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 22:19
标题: ios - 如何在先前转换的 UIView 上正确地为转换设置动画

问题摘要

无法在已翻译的 UIView 上正确执行移动和缩放动画。

当 View 事先没有被移动时,为了达到预期的效果,我先应用缩放,然后应用平移。我使用 UIViewPropertyAnimator 为生成的转换设置动画: View 在相应移动的同时放大或缩小。

但是,如果在应用此动画转换之前 View 已从其原始位置移动(翻译),我未能实现在将 View 从其新位置移动时放大或缩小的结果.

¡虽然转换问题有据可查 - 并且我在提交问题之前已经尽职尽责 - 到目前为止我未能找到成功的解决方案! p>

变形动画代码

为了便于理解和解决问题,对代码进行了简化。

extension UIView {

   func zoomAndMove(vector: CGPoint, scale: CGPoint){
      self.transform = self.transform.concatenating(CGAffineTransform(scaleX: scale.x, y: scale.y).concatenating(CGAffineTransform(translationX: vector.x, y: vector.y))
   }


   func animateZoomAndMove(from origin: CGPoint, for duration: TimeInterval, cameraZoom: CGPoint, timingFunction: UITimingCurveProvider, controlPoint2: CGPoint(x: 0.8, y: 0.7)) autoplay: Bool = false) -> UIViewPropertyAnimator {
      let animator = UIViewPropertyAnimator(duration: duration, timingParameters: timingFunction)
      let vector = CGPoint(x: self.frame.midX - origin.x, y: self.frame.midY - origin.y)

      animator.addAnimations {
         self.zoomAndMove(vector: vector, scale: cameraZoom)
      }

      if autoplay { animator.startAnimation()}
      return animator
   }
}

目前的尝试

我试图修改我的代码以返回一个转换,该转换考虑了 zoomAndMove 发生之前的先前翻译:

extension UIView {

   func zoomAndMove(vector: CGPoint, scale: CGPoint){

      if self.transform == CGAffineTransform.identity {
          self.transform = self.transform.concatenating(CGAffineTransform(scaleX: scale.x, y: scale.y).concatenating(CGAffineTransform(translationX: vector.x, y: vector.y)) 
      } else {
          let preTransform = self.transform
          self.transform = CGAffineTransform(a: scale.x, b: 0, c: 0, d: scale.y, tx: vector.x + preTransform.tx, ty: vector.y + preTransform.ty)
      }
   }

此代码不会产生预期的效果: View 跳转到新位置,正确缩放并“随机”移动。

我肯定遗漏了一些东西——我可能瞄准了错误的最终结果矩阵——但总而言之,我目前陷入困境。

如果有人知道如何执行诸如从已翻译的 UIView 缩放和移动 UIView 这样简单的任务,我将非常感谢他们的意见!

最好的,


编辑

一张图片可以抵 1,000 字,所以当我尝试实现迄今为止提出的各种建议时会发生什么(特别是 .scaledBy( 方法) :

enter image description here

你可以注意到最终的转换是正确的,但动画不是。



Best Answer-推荐答案


您是否尝试过将当前转换分配给一个属性,然后修改这个复制的属性,然后重新分配给 View ? 类似:

let originalTransform = view.transform
let scaledTransform = originalTransform.scaledBy(x: 0.2, y: 0.2)
view.transform = scaledTransform

我使用这种方法创建了一个按钮动画,效果很好,但我不确定它是否是您要找的。

关于ios - 如何在先前转换的 UIView 上正确地为转换设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935477/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4