Swift — 說說 動畫(CABasicAnimation)

Jeremy Xue
6 min readJun 8, 2018

--

前導

因為本身對於動畫效果蠻有興趣的,所以很喜歡做一些元件或是介面上的動畫效果,但都之前都著重在 UIView.animate 上,所以想要專研更特殊更多變的動畫效果,然後就找到 Swift 中的 —— CABasicAnimation ,想試試看能不能開發出更強大的動畫效果。

你可以使用繼承 init(keyPath: ) 方法創建 CABasicAnimation 的實例,指定要在渲染樹( render tree )中被進行動畫的 Key path。

當我們要開始執行一個動畫時,如同上述表達,必須宣告他為 CABasicAnimation 的實例,必指定實例的 Key path,其中我們的 Key path茲有:

  1. opacity — 不透明度
  2. backgroundColor — 背景顏色
  3. position — 座標移動
  4. transform — 變形效果

在 Swift 中我們可以告訴它這些屬性的改變,來使動畫效果產生,在製作 Swift 中的動畫效果的時候,無論是使用 UIView.animate 或是 CABasicAnimation,發現大多動畫效果都必須提供他一個初始值以及結束值,就像你在執行一個飛入動畫時,要告出它起點以及終點,或是淡入淡出的效果必須告訴他初始 alpha 值,跟結束的 alpha 值。

在我們 CABasicAnimation 中就有兩個屬性:

animation.fromValue //定義接收器用來開始的值。
animation.toValue //定義接收器用來結束的值。
animation.byValue // 定義接收器用來執行相對插值的值。

Setting Interpolation Values

fromValue、byValue 和 toValue 屬性定義了之間插值的值。全部屬性皆為 Optional 並且不得有超過兩者是 nil。其對象的類型應該與被動畫的屬性類型匹配。

插值使用方式如下:

  • 設置 fromValue 和 toValue 屬性:從 fromValue 變化到 toValue
  • 設置 fromValue 和 byValue 屬性:從 fromValue 變化到 fromValue + byValue
  • 設置 byValue 和 toValue 屬性:從 toValue — byValue 變化到 toValue
  • 設置 fromValue 屬性: 從 fromValue 變化到屬性當前值
  • 設置 toValue 屬性:從屬性當前值變化到 toValue
  • 設置 byValue 屬性:從屬性當前值變化到屬性當前值+ toValue
  • 沒有屬性被設置,在目標圖層表示層中keyPath的先前值與目標圖層表示層中keyPath的當前值之間進行插值。

簡單來說就是,假如沒有設定其中某一個值,那麼就是用這個屬性當前的值來代替。

接著我們來實作幾個範例 Apple 官方中的範例檔案來測試,首先我們先創建立一個簡單的 Layer ,之後會添加動畫到上面:

Opacity

我們會在各個範例後面加上一些屬性,才能使它運作動畫,以要實作不透明度的動畫效果為範例:

// 設定動畫 KeyPath
let animation = CABasicAnimation(keyPath: "opacity")
// 設定動畫起始值
animation.fromValue = 1
// 設定動畫結束值
animation.toValue = 0
// 動畫持續時間,必須添加否則動畫不會進行
animation.duration = 3
/* 可以下列兩項可以不需添加 */// Autoreverses 設置為 true,會從初始值進行到結束值,再由結束回到初始值
animation.autoreverses = true
// 這邊我們希望它無限輪播,所以給他一個 infinity
animation.repeatCount = Float.infinity
opacity 動畫效果呈現

BackgroundColor

let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = NSColor.red.cgColor
animation.toValue = NSColor.blue.cgColor
background 動畫效果呈現

Position

let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = [100, 100]
animation.toValue = [100, 600]
Position 動畫效果呈現

Transform

transform 的 keyPath 種類比較多,不是只有文件中的縮放,詳情可以看這篇:

let animation = CABasicAnimation(keyPath: "transform.scale.x")
animation.fromValue = 1
animation.toValue = 2
Transform scale 動畫效果呈現

接下來我們多做一個旋轉效果,但必須要把圓角效果給取消,否則會看不出在旋轉,這邊我們使用 transform.rotation :

let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = Double.pi
Transform rotation 動畫效果呈現

當然還有許多的 transform 效果,這邊就不多做呈現了。有需要的人可以去參考上面文章實作看看,本次文章到這邊結束,未來會去探討更進階的效果的文章。

--

--

Jeremy Xue

Hi, I’m Jeremy. [好想工作室 — iOS Developer]