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

圖片描述

相關文章
相關標籤/搜索