iOS动画编程-View动画[ 5 ]关键帧动画

介绍

以前咱们已经介绍了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
图片描述spa

API介绍

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

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

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

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

图片描述

相关文章
相关标签/搜索