打開任何一款 iOS 應用,幾乎都能看到過場切換、縮放、旋轉、淡入淡出這類細膩的動態效果。很多人以為這些效果背後藏著複雜的數學與渲染知識,其實在 iOS 平台上,做動畫的成本遠比想像中低。本文從最底層的圖層物件 CALayer 出發,一路走到 Core Animation 的四類動畫,最後再看 UIView 如何把這些能力包裝成一行就能呼叫的介面。
整篇的脈絡如下:
CALayer 定義在 QuartzCore 框架中,這是一個 iOS 與 Mac OS X 共用的跨平台框架。Core Animation 的工作原理,本質上是把圖層裡的內容轉成位圖,再交由硬體合成,因此想玩透動畫,第一步必須認識 CALayer。
其實在學習 Quartz 2D 繪圖時你已經用過它了:UIView 的 drawRect: 之所以能畫出東西,正是因為畫到了它自身的 layer 上,只是那層關係被 UIKit 遮住了。到了 Core Animation 這裡,我們操作的主角從 UIView 換成了 CALayer。
每個 UIView 都有一個 layer 屬性作為根圖層,根圖層之上還能掛子圖層,畫面上能看到的一切內容都裝在 layer 裡。

CALayer 的設計目標只有兩個:呈現內容、承載動畫。它不在 UIKit 中,因此不響應事件;但也正因為動畫是它的天職,許多屬性一被修改就會自動產生動畫,這類屬性被稱為「隱式動畫屬性」。
要注意的是,UIView 的根圖層是個例外:改它的屬性不會有動畫。原因很實際——根圖層多數時候扮演容器,若它一動就帶著所有子圖層一起動,反而麻煩。另外根圖層由系統建立、無法重建,但我們可以自由地往裡面加子圖層或移除子圖層。
| 屬性 | 說明 | 支援隱式動畫 |
|---|---|---|
| anchorPoint | 錨點,與 position 重合的參考點,預設 (0.5, 0.5) | 是 |
| backgroundColor | 圖層背景色 | 是 |
| borderColor / borderWidth | 邊框顏色與寬度 | 是 |
| bounds | 圖層尺寸 | 是 |
| contents | 圖層顯示的內容,例如直接放一張 CGImage | 是 |
| contentsRect | 內容顯示的範圍 | 是 |
| cornerRadius | 圓角半徑 | 是 |
| doubleSided | 背面是否顯示,預設 YES | 否 |
| frame | 位置與尺寸,本身不可動畫,實務上多用 bounds + position 取代 | 否 |
| hidden | 是否隱藏 | 是 |
| mask / masksToBounds | 遮罩,以及子圖層是否被邊界裁切(預設 NO) | 是 |
| opacity | 透明度,等同 UIView 的 alpha | 是 |
| position | 中心點位置,等同 UIView 的 center | 是 |
| shadowColor / shadowOffset / shadowOpacity / shadowRadius / shadowPath | 陰影相關;shadowOpacity 預設為 0,要看到陰影務必設定 | 是 |
| sublayers / sublayerTransform | 子圖層與子圖層整體形變 | 是 |
| transform | 圖層形變(CATransform3D) | 是 |
三個容易踩的坑:
anchorPoint 取值範圍是 0~1,代表在圖層 x、y 軸上的比例位置,而它永遠與 position 重合。這帶來一個有趣的結果:當 position 固定不動,只要改 anchorPoint,圖層顯示的位置就會跟著變。
舉例:一個 100×100 的圖層,position 在 (50,50),此時 frame 為 (0,0,100,100)。anchorPoint 預設 (0.5,0.5),兩者重合,如圖 1;把 anchorPoint 改成 (0,0),錨點跑到左上角但 position 不動,圖層便往右下偏,如圖 2;再改成 (1,1),錨點落在右下角,圖層如圖 3。

下面這個小範例建立一個正方形,把圓角半徑設為邊長的一半讓它看起來是圓形,點擊螢幕時修改圖層屬性產生動畫。注意程式沒有動到 rootLayer,因為根圖層不會有動畫:
-(void)drawMyLayer{
CGSize size = [UIScreen mainScreen].bounds.size;
CALayer *layer = [[CALayer alloc] init];
// QuartzCore 是跨平台框架,必須用 CGColor
layer.backgroundColor = [UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0].CGColor;
layer.position = CGPointMake(size.width/2, size.height/2);
layer.bounds = CGRectMake(0, 0, 50, 50);
layer.cornerRadius = 25; // 半徑等於邊長一半 → 圓形
layer.shadowColor = [UIColor grayColor].CGColor;
layer.shadowOffset = CGSizeMake(2, 2);
layer.shadowOpacity = 0.9;
[self.view.layer addSublayer:layer];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
CALayer *layer = self.view.layer.sublayers[0];
CGFloat width = layer.bounds.size.width;
width = (width == 50) ? 200 : 50;
layer.bounds = CGRectMake(0, 0, width, width);
layer.cornerRadius = width / 2;
layer.position = [[touches anyObject] locationInView:self.view];
}

用 drawRect: 繪圖,本質也是畫進圖層,但那條路徑由 UIKit 觸發,因此能用一堆 UIKit 的便利方法。若直接把內容畫進 CALayer,由於不是 UIKit 呼叫,就只能使用 Core Graphics 原生 API。
兩種做法,共通點是畫完一定要呼叫圖層的 setNeedsDisplay(是圖層的方法,不是 view 的):
drawLayer:inContext:drawInContext:指定 layer.delegate 並實作 -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 即可。這個方法雖是代理方法,卻不需要宣告遵循 CALayerDelegate,因為 CALayer 為 NSObject 做了分類擴充,所有物件都自帶這個方法。設好代理後別忘了呼叫 setNeedsDisplay,否則繪製內容不會出現。
以下示範畫一張圓形頭像,這種效果在聊天類應用裡非常常見:
-(void)viewDidLoad{
[super viewDidLoad];
CALayer *layer = [[CALayer alloc] init];
layer.bounds = CGRectMake(0, 0, 150, 150);
layer.position = CGPointMake(160, 200);
layer.cornerRadius = 75;
// 只設圓角對純色有效,圖片需要裁切子圖層才會跟著變圓
layer.masksToBounds = YES;
layer.borderColor = [UIColor whiteColor].CGColor;
layer.borderWidth = 2;
layer.delegate = self;
[self.view.layer addSublayer:layer];
[layer setNeedsDisplay];
}
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGContextSaveGState(ctx);
CGContextScaleCTM(ctx, 1, -1); // 修正 Core Graphics 座標系導致上下顛倒
CGContextTranslateCTM(ctx, 0, -150);
UIImage *image = [UIImage imageNamed:@"photo.png"];
// 座標相對於圖層,而非螢幕
CGContextDrawImage(ctx, CGRectMake(0, 0, 150, 150), image.CGImage);
CGContextRestoreGState(ctx);
}

為什麼純色設了 cornerRadius 就圓,圖片卻一定要 masksToBounds?因為把圖片畫進圖層時,系統會另外建立一個子圖層來承載它。底圖層有圓角,子圖層卻還是矩形,只有讓子圖層被底圖層裁切,圓角才會生效。這也正是「為什麼 UIImageView 的 layer 設了圓角卻沒效果」這個經典疑問的答案。
masksToBounds 與陰影天生衝突:一個要求外框不可見,一個恰好畫在外框上。解法是換個思路——用兩個同尺寸的圖層,下層專職畫陰影,上層負責顯示圖片。
CGRect bounds = CGRectMake(0, 0, 150, 150); CGPoint position = CGPointMake(160, 200); CALayer *shadowLayer = [[CALayer alloc] init]; // 下層:陰影 shadowLayer.bounds = bounds; shadowLayer.position = position; shadowLayer.cornerRadius = 75; shadowLayer.shadowColor = [UIColor grayColor].CGColor; shadowLayer.shadowOffset = CGSizeMake(2, 1); shadowLayer.shadowOpacity = 1; [self.view.layer addSublayer:shadowLayer]; CALayer *photoLayer = [[CALayer alloc] init]; // 上層:圖片 photoLayer.bounds = bounds; photoLayer.position = position; photoLayer.cornerRadius = 75; photoLayer.masksToBounds = YES; photoLayer.delegate = self; [self.view.layer addSublayer:photoLayer]; [photoLayer setNeedsDisplay];

前面靠 CGContextScaleCTM 修正顛倒,其實也可以讓圖層沿 x 軸轉 180 度,效果相同但更直觀。transform 是 CATransform3D,三維形變都有對應的便利函式:CATransform3DMakeTranslation()、CATransform3DMakeScale()、CATransform3DMakeRotation()。
// 沿 x 軸旋轉 180 度,圖片方向就正常了 photoLayer.transform = CATransform3DMakeRotation(M_PI, 1, 0, 0);
如果只是單純顯示一張圖,其實連繪圖都不必,直接指定 contents 即可,自然也不存在顛倒問題:
UIImage *image = [UIImage imageNamed:@"photo.jpg"]; [layer setContents:(id)image.CGImage]; // 必須轉成 CGImage
那為什麼還要花篇幅講形變?因為在動畫裡,形變通常不是直接賦值,而是透過 keyPath 設定:
[layer setValue:@M_PI forKeyPath:@"transform.rotation.x"];
本質相同,只是借 KVC 動態改值,而這種寫法在動畫中無比常用——它把多種形變組合成一條路徑變得輕而易舉。可用的 keyPath 清單可參考 Xcode 文件的「CATransform3D Key Paths」。
繼承 CALayer,在 drawInContext: 中繪製,同樣需要 setNeedsDisplay 才會觸發。下面把自訂圖層掛到一個 UIView 上,順便驗證「UIView 繪圖其實也是畫進圖層」這件事。
@implementation KCLayer
-(void)drawInContext:(CGContextRef)ctx{
CGContextSetRGBFillColor(ctx, 135.0/255.0, 232.0/255.0, 84.0/255.0, 1);
CGContextSetRGBStrokeColor(ctx, 135.0/255.0, 232.0/255.0, 84.0/255.0, 1);
CGContextMoveToPoint(ctx, 94.5, 33.5); // 畫一顆星
CGContextAddLineToPoint(ctx, 104.02, 47.39);
CGContextAddLineToPoint(ctx, 120.18, 52.16);
CGContextAddLineToPoint(ctx, 109.91, 65.51);
CGContextAddLineToPoint(ctx, 110.37, 82.34);
CGContextAddLineToPoint(ctx, 94.5, 76.7);
CGContextAddLineToPoint(ctx, 78.63, 82.34);
CGContextAddLineToPoint(ctx, 79.09, 65.51);
CGContextAddLineToPoint(ctx, 68.82, 52.16);
CGContextAddLineToPoint(ctx, 84.98, 47.39);
CGContextClosePath(ctx);
CGContextDrawPath(ctx, kCGPathFillStroke);
}
@end
把日誌打開就會看到清楚的呼叫鏈:UIView 顯示時,系統先為根圖層建立 CGContextRef(本質是位圖上下文),接著呼叫圖層代理的 drawLayer:inContext:;UIView 在該方法裡轉而呼叫自己的 drawRect:,而 UIGraphicsGetCurrentContext() 拿到的正是同一個上下文。這條鏈完整說明了 UIKit 繪圖與圖層繪圖的關係。

UIView 的區塊寫法確實方便,但它把細節全藏了起來,而且有幾件事做不到——比如暫停動畫、把多個動畫組合成一個整體。要拿回控制權,就得認識 Core Animation(同樣位於 QuartzCore)。

基礎動畫與關鍵幀動畫都屬於屬性動畫:開發者只給出關鍵狀態,中間的「補間動畫」由系統補完。以此觀之,基礎動畫就是只有兩個關鍵幀的關鍵幀動畫。
不用 UIView 封裝時,流程固定三步:建立動畫並指定 keyPath → 設定起始值(可省略)、結束值與其他參數 → 把動畫加到圖層上。
-(void)translationAnimation:(CGPoint)location{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
// animation.fromValue 可省略,預設取圖層當前狀態
animation.toValue = [NSValue valueWithCGPoint:location];
animation.duration = 5.0;
// animation.repeatCount = HUGE_VALF; // 無限循環
// animation.removedOnCompletion = NO; // 動畫結束後不移除
// key 等同為動畫命名,之後可用 animationForKey: 取回
[_layer addAnimation:animation forKey:@"KCAnimation_Translation"];
}

動畫跑完,圖層卻「跳」回原點。原因在於圖層動畫只是把內容轉成位圖交給硬體合成,圖層自身的屬性從未改變——不只是位置,縮放動畫結束後尺寸也一樣沒變。若這圖層屬於某個 UIView,你會發現即使它視覺上移到了別處,點擊事件仍只認原本的位置。
解法很多,最直接的是在動畫結束後把位置補寫回去。順帶示範如何透過自訂 key 在動畫物件之間傳遞資料:
-(void)translationAnimation:(CGPoint)location{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.toValue = [NSValue valueWithCGPoint:location];
animation.duration = 5.0;
animation.delegate = self;
[animation setValue:[NSValue valueWithCGPoint:location]
forKey:@"KCAnimationLocation"]; // 把終點存進動畫物件
[_layer addAnimation:animation forKey:@"KCAnimation_Translation"];
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
// 關閉隱式動畫,否則補寫位置時又會產生一段動畫
[CATransaction begin];
[CATransaction setDisableActions:YES];
_layer.position = [[anim valueForKey:@"KCAnimationLocation"] CGPointValue];
[CATransaction commit];
}
這裡出現第二個陷阱:非根圖層的可動畫屬性一旦被修改就會產生隱式動畫,於是動畫跑完還會再從原點飛一次。關閉隱式動畫要用 CATransaction 包住;另一條路是把動畫圖層設為根圖層,但本例的根圖層已經被背景佔用,只能選前者。
補充:若真要避免「瞬間回到終點」的閃跳,務必明確設定 fromValue,並在動畫開始前(同樣關閉隱式動畫)就把 position 設為終點。不過實務上做平移動畫直接用隱式動畫就好,不必繞這麼遠;上面這段主要是為了說明隱式動畫的關閉時機與動畫物件傳參技巧。
再加一點真實感:落花不會乖乖直線落下,還會邊飄邊轉。圖層形變一律以錨點為中心,旋轉圓心就是 anchorPoint。
-(void)rotationAnimation{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.toValue = [NSNumber numberWithFloat:M_PI_2 * 3];
animation.duration = 6.0;
animation.autoreverses = YES; // 轉完再轉回來
[_layer addAnimation:animation forKey:@"KCAnimation_Rotation"];
}
兩個動畫同時跑時有個細節:代理只掛在移動動畫上,否則 animationDidStop: 會被呼叫兩次。
核心動畫有一個「媒體時間」的概念。若一圈旋轉設計為 60 秒,轉到 90 度時媒體時間就是 15 秒;要暫停,把 timeOffset 設為 15 秒、speed 設為 0 即可。恢復時,把 beginTime 設為「當前媒體時間 − 暫停時的偏移量」,偏移歸零、speed 回復 1.0,動畫便無縫接續。真正讓它停下與繼續的是 speed,時間偏移只是為了畫面連貫。
-(void)animationPause{
CFTimeInterval interval = [_layer convertTime:CACurrentMediaTime() fromLayer:nil];
[_layer setTimeOffset:interval];
_layer.speed = 0;
}
-(void)animationResume{
CFTimeInterval beginTime = CACurrentMediaTime() - _layer.timeOffset;
_layer.timeOffset = 0;
_layer.beginTime = beginTime;
_layer.speed = 1.0;
}

兩個必須記住的前提:
寫過 Flash 的人對關鍵幀不陌生:你只決定幾個關鍵狀態,中間交給系統補間。它有兩種控制方式——給多組屬性值,或是一條路徑;兩者同時存在時,路徑優先。
先讓落花沿幾個折點飄落:

-(void)translationAnimation{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
// 關鍵幀動畫的起始值不能省略
NSArray *values = @[
[NSValue valueWithCGPoint:_layer.position],
[NSValue valueWithCGPoint:CGPointMake(80, 220)],
[NSValue valueWithCGPoint:CGPointMake(45, 300)],
[NSValue valueWithCGPoint:CGPointMake(55, 400)]
];
animation.values = values;
animation.duration = 8.0;
animation.beginTime = CACurrentMediaTime() + 2; // 延遲兩秒
[_layer addAnimation:animation forKey:@"KCAnimation_Position"];
}

好看一些了,但每段路徑仍是直線。想真正飄起來,就換成路徑版本,用貝茲曲線描述軌跡:

-(void)translationAnimation{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
CGPathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, _layer.position.x, _layer.position.y);
CGPathAddCurveToPoint(path, NULL, 160, 280, -30, 300, 55, 400);
animation.path = path;
CGPathRelease(path);
animation.duration = 8.0;
[_layer addAnimation:animation forKey:@"KCAnimation_Position"];
}

路徑型動畫會從路徑的起點開始跑到終點。若路徑是矩形,就從左上角順時針繞一圈;若是橢圓,則從右側(0 度)順時針一圈回到原處。
keyTimes:控制每個關鍵幀占用的時間比例。四個關鍵幀預設均分,8 秒動畫即每 8/3 秒一幀。若想讓第 1→2 幀用掉一半時間、第 2→3 與 3→4 各用四分之一,就傳入 0.0、0.5、0.75、1.0(需包成 NSNumber)。
calculationMode:決定幀間如何補。

真實世界的運動幾乎都是複合運動,但屬性動畫一次只能處理一個屬性。動畫一多,逐一控制很快就變成噩夢——動畫組就是為此而生:把多個動畫放進一個容器,公共行為統一設定,組內動畫並發執行。
-(void)groupAnimation{
CAAnimationGroup *group = [CAAnimationGroup animation];
CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotation.toValue = [NSNumber numberWithFloat:M_PI_2 * 3];
rotation.autoreverses = YES;
rotation.repeatCount = HUGE_VALF;
rotation.removedOnCompletion = NO;
[rotation setValue:[NSNumber numberWithFloat:M_PI_2 * 3]
forKey:@"KCProperty_ToValue"];
CAKeyframeAnimation *translation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
CGPathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, _layer.position.x, _layer.position.y);
CGPathAddCurveToPoint(path, NULL, 160, 280, -30, 300, 55, 400);
translation.path = path;
CGPathRelease(path);
[translation setValue:[NSValue valueWithCGPoint:CGPointMake(55, 400)]
forKey:@"KCProperty_EndPosition"];
group.animations = @[rotation, translation];
group.delegate = self;
group.duration = 10.0; // 組內動畫若已自設時長則此處不生效
group.beginTime = CACurrentMediaTime() + 5; // 延遲五秒
[_layer addAnimation:group forKey:nil];
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
CAAnimationGroup *group = (CAAnimationGroup *)anim;
CGFloat toValue = [[group.animations[0] valueForKey:@"KCProperty_ToValue"] floatValue];
CGPoint endPoint = [[group.animations[1] valueForKey:@"KCProperty_EndPosition"] CGPointValue];
[CATransaction begin];
[CATransaction setDisableActions:YES];
_layer.position = endPoint;
_layer.transform = CATransform3DMakeRotation(toValue, 0, 0, 1);
[CATransaction commit];
}

轉場負責的是「從一個場景過渡到另一個場景」,三步搞定:建立 CATransition → 設定類型、子類型與時長 → 換上新的顯示內容並把動畫加到圖層。
| 類型 | 說明 | 常量 | 可設方向 |
|---|---|---|---|
| fade | 淡入淡出 | kCATransitionFade | 是 |
| moveIn | 新視圖移入覆蓋舊視圖 | kCATransitionMoveIn | 是 |
| push | 新視圖把舊視圖推走 | kCATransitionPush | 是 |
| reveal | 舊視圖移開露出新視圖 | kCATransitionReveal | 是 |
| cube | 立方體翻轉(私有 API,字串呼叫) | 無常量 | 是 |
| oglFlip | 翻轉(私有 API) | 無常量 | 是 |
| suckEffect | 收縮(私有 API) | 無常量 | 否 |
| rippleEffect | 水滴波紋(私有 API) | 無常量 | 否 |
| pageCurl / pageUnCurl | 向上/向下翻頁(私有 API) | 無常量 | 是 |
| cameraIrisHollowOpen / Close | 鏡頭開合(私有 API) | 無常量 | 否 |
支援方向的類型可以再指定子類型:kCATransitionFromRight、FromLeft、FromTop、FromBottom。私有 API 未經 Apple 公開,只能以字串指定,上架時需自行評估風險。
用一個 UIImageView 加轉場動畫,就能做出效果很不錯的循環相簿,程式碼短得驚人:
-(void)transitionAnimation:(BOOL)isNext{
CATransition *transition = [[CATransition alloc] init];
transition.type = @"cube"; // 私有類型只能用字串
transition.subtype = isNext ? kCATransitionFromRight : kCATransitionFromLeft;
transition.duration = 1.0;
_imageView.image = [self getImage:isNext]; // 先換內容
[_imageView.layer addAnimation:transition forKey:@"KCTransition"];
}
-(UIImage *)getImage:(BOOL)isNext{
_currentIndex = isNext ? (_currentIndex + 1) % IMAGE_COUNT
: (_currentIndex - 1 + IMAGE_COUNT) % IMAGE_COUNT;
return [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", _currentIndex]];
}

有些運動無法用屬性動畫描述,只能一幀一幀畫,例如人物動作。最直覺的做法是設 UIImageView 的 animationImages 再 startAnimating,但這種方式會一次載入大量圖片、且播放過程無法介入。改用 NSTimer 定時換圖可以解決載入問題,卻仍受系統繁忙影響而掉幀。
CADisplayLink 是更好的選擇。它也是計時器,但刷新週期與螢幕同步(iOS 通常為每秒 60 次),加入主 RunLoop 後會隨主循環持續呼叫目標方法,因此幾乎感覺不到停頓,這類動畫也被稱為「時鐘動畫」。
代價是效能:逐幀動畫天生較貴,因此迴圈內一定要壓低演算法複雜度、控制記憶體峰值。實務上常把會重複使用的小圖預先快取,避免在迴圈裡反覆建立 UIImage。
-(void)viewDidLoad{
[super viewDidLoad];
self.view.layer.contents = (id)[UIImage imageNamed:@"bg.png"].CGImage;
_layer = [[CALayer alloc] init];
_layer.bounds = CGRectMake(0, 0, 87, 32);
_layer.position = CGPointMake(160, 284);
[self.view.layer addSublayer:_layer];
// 預先快取,別在迴圈裡反覆解碼
_images = [NSMutableArray array];
for (int i = 0; i < 10; ++i) {
[_images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"fish%i.png", i]]];
}
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
-(void)step{
static int s = 0;
if (++s % 10 == 0) { // 約每秒換 6 幀
_layer.contents = (id)[_images[_index] CGImage];
_index = (_index + 1) % IMAGE_COUNT;
}
}

懂了核心動畫的原理,UIView 的封裝可說一學就會。日常開發中九成以上的動畫需求,用這層封裝都能解決。
非根圖層直接設屬性就有隱式動畫,所以示範時改用 UIImageView 承載落花,才看得出封裝的價值。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint location = [[touches anyObject] locationInView:self.view];
// duration 時長、delay 延遲、options 行為、completion 完成回調
[UIView animateWithDuration:5.0
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{ _imageView.center = location; }
completion:^(BOOL finished){ NSLog(@"Animation end."); }];
}
舊式的 begin/commit 寫法也仍然可用,能設定重複次數、是否自動回覆、開始時間與代理方法:
[UIView beginAnimations:@"KCBasicAnimation" context:nil]; [UIView setAnimationDuration:5.0]; _imageView.center = location; [UIView commitAnimations];
iOS 7 之後,Apple 直接提供了彈性動畫的 API,damping 越小彈性越明顯:
[UIView animateWithDuration:5.0
delay:0
usingSpringWithDamping:0.1
initialSpringVelocity:1.0
options:UIViewAnimationOptionCurveLinear
animations:^{ _imageView.center = location; }
completion:nil];

UIViewAnimationOptions 是三類可組合的選項。
常規行為(可多選):LayoutSubviews(子視圖跟著動)、AllowUserInteraction(動畫期間可互動)、BeginFromCurrentState(從當前狀態開始)、Repeat、Autoreverse、OverrideInheritedDuration、OverrideInheritedCurve、OverrideInheritedOptions、AllowAnimatedContent(動畫中重繪,僅轉場)、ShowHideTransitionViews(切換時隱藏而非移除舊視圖,僅轉場)。
速度曲線(單選):CurveEaseInOut(先慢後快)、CurveEaseIn(逐漸變慢)、CurveEaseOut(逐漸加速)、CurveLinear(等速,預設)。
轉場類型(單選,僅轉場):TransitionNone、FlipFromLeft / Right / Top / Bottom、CurlUp / CurlDown、CrossDissolve。
從 iOS 7 起,UIView 也封裝了關鍵幀動畫,用相對起始時間與相對持續時間描述每一幀:
[UIView animateKeyframesWithDuration:5.0
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
// 起始位置算第一幀,以下依序為第二、三、四幀
[UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
_imageView.center = CGPointMake(80.0, 220.0); // 0 → 2.5 秒
}];
[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.25 animations:^{
_imageView.center = CGPointMake(45.0, 300.0); // 2.5 → 3.75 秒
}];
[UIView addKeyframeWithRelativeStartTime:0.75 relativeDuration:0.25 animations:^{
_imageView.center = CGPointMake(55.0, 400.0); // 3.75 → 5 秒
}];
} completion:^(BOOL finished){ NSLog(@"Animation end."); }];
關鍵幀的 options 分兩類:常規行為與核心動畫同名的那些(LayoutSubviews、AllowUserInteraction、BeginFromCurrentState、Repeat、Autoreverse、OverrideInheritedDuration、OverrideInheritedOptions),以及計算模式(CalculationModeLinear / Discrete / Paced / Cubic / CubicPaced),與前面介紹的五種模式一一對應。
要注意:UIView 目前只支援屬性值型關鍵幀,路徑型仍須回到 Core Animation。
-(void)transitionAnimation:(BOOL)isNext{
UIViewAnimationOptions option = isNext
? (UIViewAnimationOptionCurveLinear | UIViewAnimationOptionTransitionFlipFromRight)
: (UIViewAnimationOptionCurveLinear | UIViewAnimationOptionTransitionFlipFromLeft);
[UIView transitionWithView:_imageView
duration:1.0
options:option
animations:^{ _imageView.image = [self getImage:isNext]; }
completion:nil];
}
上面只有一個視圖在換內容。若要在兩個版面配置完全不同的複雜視圖之間轉場,改用 transitionFromView:toView:duration:options:completion:。預設轉出的視圖會被移除、轉入後再加回;加上 UIViewAnimationOptionShowHideTransitionViews 則改為隱藏而非移除。
最後提醒兩點:轉場的 options 與基礎動畫完全一致;但透過 UIView 做轉場時可用效果較少,因為拿不到私有 API。