代码之家  ›  专栏  ›  技术社区  ›  fs_tigre

如何消除animateKeyframes动画开始和结束时的延迟-Swift UIKit

  •  0
  • fs_tigre  · 技术社区  · 5 年前

    有没有办法消除animateKeyframes动画开始和结束时的延迟?

    正如你所看到的,动画开始前有一点延迟;在点击 Animate 按钮,也在动画的末尾。我想能做的是在动画开始后尽快开始 使有生气 点击按钮是为了向用户提供反馈。

    这是使用时的正常行为吗 animateKeyframes 使用 calculationModeCubic ? 有没有办法让动画在点击按钮后立即启动?

    enter image description here

    抱歉拼写错误(Aniamate)。

    以下是代码:

    @IBAction func startAnimation(_ sender: Any) {
        addMyView()
        
        UIView.animateKeyframes(withDuration: 3.0, delay: 0.0, options: [.calculationModeCubic], animations: {
            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {
                self.myView!.center =  CGPoint(x: self.pointA.center.x, y: self.pointA.center.y)
            })
            UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.2, animations: {
                self.myView!.center =  CGPoint(x: self.pointB.center.x + 55, y: self.pointB.center.y - 5 )
                self.myView!.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
            })
            
            UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.2, animations: {
                self.myView!.center =  CGPoint(x: self.pointB.center.x, y: self.pointB.center.y)
                self.myView!.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
            })
        }, completion: { _ in
            self.myView?.removeFromSuperview()
        })
    }
    
    func addMyView(){
        myView = UIView(frame: CGRect(x: pointA.center.x - 25, y: pointA.center.y - 25, width: 50, height: 50))
        myView?.backgroundColor = .blue
        myView?.layer.cornerRadius = myView!.frame.height / 2
        view.addSubview(myView!)
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   fs_tigre    5 年前

    关键是要不断调整 withRelativeStartTime: 还有 relativeDuration: 参数。

    @IBAction func startAnimation(_ sender: Any) {
        addMyView()
          UIView.animateKeyframes(withDuration: 1.5, delay: 0.0, options: [.calculationModeCubic], animations: {
            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {
                self.myView!.center =  CGPoint(x: self.pointA.center.x, y: self.pointA.center.y)
            })
            UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.9, animations: {
                self.myView!.center =  CGPoint(x: self.pointB.center.x + 75, y: self.pointB.center.y - 50 )
                self.myView!.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
            })
            
            UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.7, animations: {
                self.myView!.center =  CGPoint(x: self.pointB.center.x, y: self.pointB.center.y)
                self.myView!.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
            })
        }, completion: { _ in
            self.myView?.removeFromSuperview()
        })      
    
    }