CAAnimation 底層有一個關鍵協議叫 CAMediaTiming,CABasicAnimation 與 CAKeyframeAnimation 都建立在它之上。像 duration、beginTime、repeatCount 這些與時間有關的屬性,全都定義在這裡。
協議一共定義了 8 個屬性,它們彼此以某種方式組合,精確地控制著動畫的節奏。蘋果的官方文件對每個屬性只寫了寥寥數句,讀起來容易一知半解。本文試著把「時間」這件事講得更具體一些——想像一條時間軸,每一格代表一秒,動畫就在這條軸上從起點走到終點。
由於 CALayer 與 CAAnimation 都實作了 CAMediaTiming,理解這些屬性對寫 Core Animation 幾乎是必備功課。
1. repeatCount — 動畫重複次數,可設為小數。設為 HUGE_VALF 代表無限次重複。
2. repeatDuration — 動畫的總時長。若大於單次時長則重複播放,若小於單次時長則被截斷。
3. duration — 單次動畫的持續時間。
4. speed — 圖層或動畫相對於父層 CALayer 的時間流速。設為 2 就是兩倍速,設為 0 則時間凍結——這正是暫停動畫的原理。
5. fillMode — 動畫有效期結束後,呈現效果是凍結還是移除。
6. beginTime — 相對於父物件的開始時間,基準是系統的絕對時間:
/** 當前時間 2 秒後才開始動畫 */ keyFrameAnim.beginTime = CACurrentMediaTime() + 2; /** 假設動畫已執行 2 秒(若這個值大於動畫時長,代表動畫其實早已結束) */ keyFrameAnim.beginTime = CACurrentMediaTime() - 2;
7. timeOffset — 時間軸偏移量,把時間軸挪到偏移位置再跑完整個動畫時長。例如動畫長 3 秒、偏移量設為 8,則起始位置相當於 8 % 3 = 2 秒處,跑完 3 秒後在整體時長的 1/3 位置結束。
8. CACurrentMediaTime — 回傳系統目前的絕對時間(自開機起算),單位為秒。它是 Core Animation 世界的「現在幾點」。
/** 預設。動畫開始前不顯示,結束後移除。 */ kCAFillModeRemoved; /** 動畫開始前不顯示,但結束後保留最終狀態。 */ kCAFillModeForwards; /** 動畫開始前先顯示初始狀態,結束後移除。 */ kCAFillModeBackwards; /** 開始前顯示初始狀態,結束後仍保留最終狀態。 */ kCAFillModeBoth;
實務上最常被忘記的就是這一段:動畫播完後模型層級會「啪」地跳回原樣,多半是因為沒設 kCAFillModeForwards。
利用 speed 與 timeOffset 的組合,就能做出真正的暫停/繼續:
- (IBAction)pauseBtnClicked:(id)sender {
// 確認該圖層上是否有名為 position 的動畫
if ([self.layer.presentationLayer animationForKey:@"position"]) {
// 把絕對時間換算成圖層自身的本地時間
CFTimeInterval localTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
self.layer.speed = 0; // 時間流速歸零 → 暫停
self.layer.timeOffset = localTime; // 記住停在哪裡
}
}
- (IBAction)continueBtnClicked:(id)sender {
if ([self.layer.presentationLayer animationForKey:@"position"]) {
CFTimeInterval timeOffset = self.layer.timeOffset;
self.layer.timeOffset = 0; // 重置偏移
self.layer.speed = 1; // 恢復正常流速
self.layer.beginTime = 0;
CFTimeInterval localTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
CFTimeInterval timeSincePause = localTime - timeOffset;
self.layer.beginTime = timeSincePause; // 從上次暫停處接續
}
}
核心概念其實只有一句:speed = 0 讓時間停止流動,timeOffset 記住進度,恢復時再把兩者還原並重新對齊 beginTime。
以上就是本文的全部內容,希望能幫助到大家。