介绍

之前我们已经介绍了View动画的大部分内容,但是还有一个问题我们没有解决
如果我们的动画想构成一个链条,我们只能用多个动画去实现,比如下面的例子
图片描述
按照我们之前学习到的方法,我们应该这样去实现

UIView.animateWithDuration(0.5, animations: { view.center.x += 200.0
}, completion: { _ in UIView.animateWithDuration(0.5, animations: {
view.center.y += 100.0 }, completion: { _ in
UIView.animateWithDuration(0.5, animations: { view.center.x -= 200.0
}, completion: { _ in
UIView.animateWithDuration(0.5, animations: { view.center.y -= 100.0
}) })
}) })

这样的代码显然不够优雅,那我们应该怎么去实现这样的动画呢?
这里我们就需要用到关键帧动画

Keyframe animations

继续我们上次的Demo
图片描述

API介绍

这是关键帧动画最关键的方法之一,我们的关键帧就放在这个方法中

UIView.animateKeyframesWithDuration(1.5, delay: 0.0, options: [], animations: {
//add keyframes
}, completion: nil)

这个方法即每一个关键帧
第一个参数为开始时间,第二个参数为动画持续时间

      UIView.addKeyframeWithRelativeStartTime(0.51, relativeDuration: 0.01) {
        //add animations
}

Demo实现

  func planeDepart() {
    let originalCenter = planeImage.center
    
    UIView.animateKeyframesWithDuration(1.5, delay: 0.0, options: [], animations: {
      //add keyframes
      
      UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.25, animations: {
        self.planeImage.center.x += 80.0
        self.planeImage.center.y -= 10.0
      })
      
      UIView.addKeyframeWithRelativeStartTime(0.1, relativeDuration: 0.4) {
        self.planeImage.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4/2))
      }
      
      UIView.addKeyframeWithRelativeStartTime(0.25, relativeDuration: 0.25) {
        self.planeImage.center.x += 100.0
        self.planeImage.center.y -= 50.0
        self.planeImage.alpha = 0.0
      }
      
      UIView.addKeyframeWithRelativeStartTime(0.51, relativeDuration: 0.01) {
        self.planeImage.transform = CGAffineTransformIdentity
        self.planeImage.center = CGPoint(x: 0.0, y: originalCenter.y)
      }
      
      UIView.addKeyframeWithRelativeStartTime(0.55, relativeDuration: 0.45) {
        self.planeImage.alpha = 1.0
        self.planeImage.center = originalCenter
      }
      
      }, completion: nil)
  }

图片描述


Hydrogen
2.5k 声望73 粉丝

Write code for fun.