前言:在APP程序開發(fā)中,優(yōu)美的界面能夠大大提高用戶的體驗,而優(yōu)美的界面離不開好看的動畫效果。下面廢話少說,直接進入主題。
在iOS實際開發(fā)中常用的動畫無非是以下四種:UIView動畫,核心動畫,幀動畫,自定義轉(zhuǎn)場動畫。下面我們逐個介紹。
1.UIView動畫
能實現(xiàn)UIView動畫的屬性
UIView動畫是iOS開發(fā)中最廉價也是最常用的動畫。
UIView動畫能夠設置的動畫屬性有:
- frame
- bounds
- center
- transform
- alpha
- backgroundColor
- contentStretch
UIView動畫實現(xiàn)方式
UIView動畫實現(xiàn)方式有普通方式和Block方式,不過平常我們一般會直接使用Block的方式。簡單,粗暴,管用!
先說說普通方式實現(xiàn)動畫。
開始動畫語句:
// 第一個參數(shù): 動畫標識
// 第二個參數(shù): 附加參數(shù),在設置代理情況下,此參數(shù)將發(fā)送到setAnimationWillStartSelector和setAnimationDidStopSelector所指定的方法,大部分情況,設置為nil.
[UIView beginAnimations:(nullable NSString *) context:(nullable void *)];
結(jié)束動畫語句:
[UIView commitAnimations];
動畫參數(shù)的屬性設置:
//動畫持續(xù)時間
[UIView setAnimationDuration:(NSTimeInterval)];
//動畫的代理對象
[UIView setAnimationDelegate:(nullable id)];
//設置動畫將開始時代理對象執(zhí)行的SEL
[UIView setAnimationWillStartSelector:(nullable SEL)];
//設置動畫延遲執(zhí)行的時間
[UIView setAnimationDelay:(NSTimeInterval)];
//設置動畫的重復次數(shù)
[UIView setAnimationRepeatCount:(float)];
//設置動畫的曲線
/*
UIViewAnimationCurve的枚舉值:
UIViewAnimationCurveEaseInOut, // 慢進慢出(默認值)
UIViewAnimationCurveEaseIn, // 慢進
UIViewAnimationCurveEaseOut, // 慢出
UIViewAnimationCurveLinear // 勻速
*/
[UIView setAnimationCurve:(UIViewAnimationCurve)];
//設置是否從當前狀態(tài)開始播放動畫
/*假設上一個動畫正在播放,且尚未播放完畢,我們將要進行一個新的動畫:
當為YES時:動畫將從上一個動畫所在的狀態(tài)開始播放
當為NO時:動畫將從上一個動畫所指定的最終狀態(tài)開始播放(此時上一個動畫馬上結(jié)束)*/
[UIView setAnimationBeginsFromCurrentState:YES];
//設置動畫是否繼續(xù)執(zhí)行相反的動畫
[UIView setAnimationRepeatAutoreverses:(BOOL)];
//是否禁用動畫效果(對象屬性依然會被改變,只是沒有動畫效果)
[UIView setAnimationsEnabled:(BOOL)];
//設置視圖的過渡效果
/* 第一個參數(shù):UIViewAnimationTransition的枚舉值如下
UIViewAnimationTransitionNone, //不使用動畫
UIViewAnimationTransitionFlipFromLeft, //從左向右旋轉(zhuǎn)翻頁
UIViewAnimationTransitionFlipFromRight, //從右向左旋轉(zhuǎn)翻頁
UIViewAnimationTransitionCurlUp, //從下往上卷曲翻頁
UIViewAnimationTransitionCurlDown, //從上往下卷曲翻頁
第二個參數(shù):需要過渡效果的View
第三個參數(shù):是否使用視圖緩存,YES:視圖在開始和結(jié)束時渲染一次;NO:視圖在每一幀都渲染*/
[UIView setAnimationTransition:(UIViewAnimationTransition) forView:(nonnull UIView *) cache:(BOOL)];
下面列出三個??:

代碼如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *tuch = touches.anyObject;
CGPoint point = [tuch locationInView:self.view];
[UIView beginAnimations:@"testAnimation" context:nil];
[UIView setAnimationDuration:3.0];
[UIView setAnimationDelegate:self];
//設置動畫將開始時代理對象執(zhí)行的SEL
[UIView setAnimationWillStartSelector:@selector(animationDoing)];
//設置動畫延遲執(zhí)行的時間
[UIView setAnimationDelay:0];
[UIView setAnimationRepeatCount:MAXFLOAT];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
//設置動畫是否繼續(xù)執(zhí)行相反的動畫
[UIView setAnimationRepeatAutoreverses:YES];
self.redView.center = point;
self.redView.transform = CGAffineTransformMakeScale(1.5, 1.5);
self.redView.transform = CGAffineTransformMakeRotation(M_PI);
[UIView commitAnimations];
}

代碼如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 轉(zhuǎn)成動畫 (flip)
[UIView beginAnimations:@"imageViewTranslation" context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationDelegate:self];
[UIView setAnimationWillStartSelector:@selector(startAnimation)];
[UIView setAnimationDidStopSelector:@selector(stopAnimation)];
[UIView setAnimationRepeatCount:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationRepeatCount:MAXFLOAT];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.imageView cache:YES];
if (++count % 2 ==0) {
self.imageView.image = [UIImage imageNamed:@"yh_detial_ty"];
}else{
self.imageView.image = [UIImage imageNamed:@"yh_detial_bz"];
}
[UIView commitAnimations];
}

代碼如下:
[UIView beginAnimations:@"test" context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationRepeatCount:MAXFLOAT];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.redView cache:YES];
[UIView commitAnimations];
UIView Block 動畫
ios4.0以后增加了Block動畫塊,提供了更簡潔的方式來實現(xiàn)動畫.日常開發(fā)中一般也是使用Block形式創(chuàng)建動畫。
最簡潔的Block動畫:包含時間和動畫:
[UIView animateWithDuration:(NSTimeInterval) //動畫持續(xù)時間
animations:^{
//執(zhí)行的動畫
}];
帶有動畫提交回調(diào)的Block動畫
[UIView animateWithDuration:(NSTimeInterval) //動畫持續(xù)時間
animations:^{
//執(zhí)行的動畫
} completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
可以設置延時時間和過渡效果的Block動畫
[UIView animateWithDuration:(NSTimeInterval) //動畫持續(xù)時間
delay:(NSTimeInterval) //動畫延遲執(zhí)行的時間
options:(UIViewAnimationOptions) //動畫的過渡效果
animations:^{
//執(zhí)行的動畫
} completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
UIViewAnimationOptions的枚舉值如下,可組合使用:
UIViewAnimationOptionLayoutSubviews //進行動畫時布局子控件
UIViewAnimationOptionAllowUserInteraction //進行動畫時允許用戶交互
UIViewAnimationOptionBeginFromCurrentState //從當前狀態(tài)開始動畫
UIViewAnimationOptionRepeat //無限重復執(zhí)行動畫
UIViewAnimationOptionAutoreverse //執(zhí)行動畫回路
UIViewAnimationOptionOverrideInheritedDuration //忽略嵌套動畫的執(zhí)行時間設置
UIViewAnimationOptionOverrideInheritedCurve //忽略嵌套動畫的曲線設置
UIViewAnimationOptionAllowAnimatedContent //轉(zhuǎn)場:進行動畫時重繪視圖
UIViewAnimationOptionShowHideTransitionViews //轉(zhuǎn)場:移除(添加和移除圖層的)動畫效果
UIViewAnimationOptionOverrideInheritedOptions //不繼承父動畫設置
UIViewAnimationOptionCurveEaseInOut //時間曲線,慢進慢出(默認值)
UIViewAnimationOptionCurveEaseIn //時間曲線,慢進
UIViewAnimationOptionCurveEaseOut //時間曲線,慢出
UIViewAnimationOptionCurveLinear //時間曲線,勻速
UIViewAnimationOptionTransitionNone //轉(zhuǎn)場,不使用動畫
UIViewAnimationOptionTransitionFlipFromLeft //轉(zhuǎn)場,從左向右旋轉(zhuǎn)翻頁
UIViewAnimationOptionTransitionFlipFromRight //轉(zhuǎn)場,從右向左旋轉(zhuǎn)翻頁
UIViewAnimationOptionTransitionCurlUp //轉(zhuǎn)場,下往上卷曲翻頁
UIViewAnimationOptionTransitionCurlDown //轉(zhuǎn)場,從上往下卷曲翻頁
UIViewAnimationOptionTransitionCrossDissolve //轉(zhuǎn)場,交叉消失和出現(xiàn)
UIViewAnimationOptionTransitionFlipFromTop //轉(zhuǎn)場,從上向下旋轉(zhuǎn)翻頁
UIViewAnimationOptionTransitionFlipFromBottom //轉(zhuǎn)場,從下向上旋轉(zhuǎn)翻頁
Spring動畫
ios7.0以后新增了Spring動畫(IOS系統(tǒng)動畫大部分采用Spring Animation, 適用所有可被添加動畫效果的屬性)
[UIView animateWithDuration:(NSTimeInterval)//動畫持續(xù)時間
delay:(NSTimeInterval)//動畫延遲執(zhí)行的時間
usingSpringWithDamping:(CGFloat)//震動效果,范圍0~1,數(shù)值越小震動效果越明顯
initialSpringVelocity:(CGFloat)//初始速度,數(shù)值越大初始速度越快
options:(UIViewAnimationOptions)//動畫的過渡效果
animations:^{
//執(zhí)行的動畫
}
completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
Keyframes動畫
IOS7.0后新增了關鍵幀動畫,支持屬性關鍵幀,不支持路徑關鍵幀
[UIView animateKeyframesWithDuration:(NSTimeInterval)//動畫持續(xù)時間
delay:(NSTimeInterval)//動畫延遲執(zhí)行的時間
options:(UIViewKeyframeAnimationOptions)//動畫的過渡效果
animations:^{
//執(zhí)行的關鍵幀動畫
}
completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
UIViewKeyframeAnimationOptions的枚舉值如下,可組合使用:
UIViewAnimationOptionLayoutSubviews //進行動畫時布局子控件
UIViewAnimationOptionAllowUserInteraction //進行動畫時允許用戶交互
UIViewAnimationOptionBeginFromCurrentState //從當前狀態(tài)開始動畫
UIViewAnimationOptionRepeat //無限重復執(zhí)行動畫
UIViewAnimationOptionAutoreverse //執(zhí)行動畫回路
UIViewAnimationOptionOverrideInheritedDuration //忽略嵌套動畫的執(zhí)行時間設置
UIViewAnimationOptionOverrideInheritedOptions //不繼承父動畫設置
UIViewKeyframeAnimationOptionCalculationModeLinear //運算模式 :連續(xù)
UIViewKeyframeAnimationOptionCalculationModeDiscrete //運算模式 :離散
UIViewKeyframeAnimationOptionCalculationModePaced //運算模式 :均勻執(zhí)行
UIViewKeyframeAnimationOptionCalculationModeCubic //運算模式 :平滑
UIViewKeyframeAnimationOptionCalculationModeCubicPaced //運算模式 :平滑均勻
各種運算模式的直觀比較如下圖:

增加關鍵幀方法:
[UIView addKeyframeWithRelativeStartTime:(double)//動畫開始的時間(占總時間的比例)
relativeDuration:(double) //動畫持續(xù)時間(占總時間的比例)
animations:^{
//執(zhí)行的動畫
}];
轉(zhuǎn)場動畫:
a.從舊視圖到新視圖的動畫效果
[UIView transitionFromView:(nonnull UIView *) toView:(nonnull UIView *) duration:(NSTimeInterval) options:(UIViewAnimationOptions) completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
在該動畫過程中,fromView 會從父視圖中移除,并將 toView 添加到父視圖中,注意轉(zhuǎn)場動畫的作用對象是父視圖(過渡效果體現(xiàn)在父視圖上)。調(diào)用該方法相當于執(zhí)行下面兩句代碼:
[fromView.superview addSubview:toView];
[fromView removeFromSuperview];
單個視圖的過渡效果
[UIView transitionWithView:(nonnull UIView *)
duration:(NSTimeInterval)
options:(UIViewAnimationOptions)
animations:^{
//執(zhí)行的動畫
}
completion:^(BOOL finished) {
//動畫執(zhí)行提交后的操作
}];
下面依舊舉兩個??:

代碼如下:
[UIView animateWithDuration:3.0 animations:^{
self.redView.center = point;
self.redView.transform = CGAffineTransformMakeScale(1.5, 1.5);
self.redView.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
[UIView animateWithDuration:2.0 animations:^{
self.redView.frame = CGRectMake(100, 100, 100, 100);
self.redView.transform = CGAffineTransformMakeScale(1 / 1.5,1 / 1.5);
self.redView.transform = CGAffineTransformMakeRotation(M_PI);
}];
}];

代碼如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.redView.alpha = 0;
/*
animateWithDuration 動畫持續(xù)時間
delay 動畫延遲執(zhí)行的時間
usingSpringWithDamping 震動效果,范圍0~1,數(shù)值越小震動效果越明顯
initialSpringVelocity 初始速度,數(shù)值越大初始速度越快
options 動畫的過渡效果
*/
[UIView animateWithDuration:3.0 delay:1.0 usingSpringWithDamping:0.3 initialSpringVelocity:1 options:UIViewAnimationOptionAllowUserInteraction animations:^{
self.redView.alpha = 1.0;
self.redView.frame = CGRectMake(200, 350, 140, 140);
} completion:^(BOOL finished) {
[self.redView removeFromSuperview];
}];
}
2.核心動畫
說道核心動畫,那就不得不先說下CALayer。
- 在iOS系統(tǒng)中,你能看得見摸得著的東西基本上都是UIView,比如一個按鈕、一個文本標簽、一個文本輸入框、一個圖標等等,這些都是UIView。
- 其實UIView之所以能顯示在屏幕上,完全是因為它內(nèi)部的一個層。
- 在創(chuàng)建UIView對象時,UIView內(nèi)部會自動創(chuàng)建一個層(即CALayer對象),通過UIView的layer屬性可以訪問這個層。當UIView需要顯示到屏幕上時,會調(diào)用drawRect:方法進行繪圖,并且會將所有內(nèi)容繪制在自己的層上,繪圖完畢后,系統(tǒng)會將層拷貝到屏幕上,于是就完成了UIView的顯示。
- 換句話說,UIView本身不具備顯示的功能,是它內(nèi)部的層才有顯示功能。
上面已經(jīng)說過了,UIView之所以能夠顯示,完全是因為內(nèi)部的CALayer對象。因此,通過操作這個CALayer對象,可以很方便地調(diào)整UIView的一些界面屬性,比如:陰影、圓角大小、邊框?qū)挾群皖伾取?/p>
//下面是CALayer的一些屬性介紹
//寬度和高度
@property CGRect bounds;
//位置(默認指中點,具體由anchorPoint決定)
@property CGPoint position;
//錨點(x,y的范圍都是0-1),決定了position的含義
@property CGPoint anchorPoint;
//背景顏色(CGColorRef類型)
@propertyCGColorRefbackgroundColor;
//形變屬性
@property CATransform3D transform;
//邊框顏色(CGColorRef類型)
@property CGColorRef borderColor;
//邊框?qū)挾?@property CGFloat borderWidth;
//圓角半徑
@property CGFloat cornerRadius;
//內(nèi)容(比如設置為圖片CGImageRef)
@property(retain) id contents;
說明:可以通過設置contents屬性給UIView設置背景圖片,注意必須是CGImage才能顯示,我們可以在UIImage對象后面加上.CGImage直接轉(zhuǎn)換,轉(zhuǎn)換之后還需要在前面加上(id)進行強轉(zhuǎn)。
// 跨框架賦值需要進行橋接
self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"123"].CGImage);
值得注意的是,UIView的CALayer對象(層)通過layer屬性可以訪問這個層。要注意的是,這個默認的層不允許重新創(chuàng)建,但可以往層里面添加子層。UIView可以通過addSubview:方法添加子視圖,類似地,CALayer可以通過addSublayer:方法添加子層
CALayer對象有兩個比較重要的屬性,那就是position和anchorPoint。
- position和anchorPoint屬性都是CGPoint類型的
- position可以用來設置CALayer在父層中的位置,它是以父層的左上角為坐標原點(0, 0)
- anchorPoint稱為"定位點",它決定著CALayer身上的哪個點會在position屬性所指的位置。它的x、y取值范圍都是0~1,默認值為(0.5, 0.5)
1.創(chuàng)建一個CALayer,添加到控制器的view的layer中
CALayer *myLayer = [CALayer layer];
// 設置層的寬度和高度(100x100)
myLayer.bounds = CGRectMake(0, 0, 100, 100);
// 設置層的位置
myLayer.position = CGPointMake(100, 100);
// 設置層的背景顏色:紅色
myLayer.backgroundColor = [UIColor redColor].CGColor;
// 添加myLayer到控制器的view的layer中
[self.view.layer addSublayer:myLayer];
第5行設置了myLayer的position為(100, 100),又因為anchorPoint默認是(0.5, 0.5),所以最后的效果是:myLayer的中點會在父層的(100, 100)位置

注意,藍色線是我自己加上去的,方便大家理解,并不是默認的顯示效果。兩條藍色線的寬度均為100。
2.若將anchorPoint改為(0, 0),myLayer的左上角會在(100, 100)位置
1 myLayer.anchorPoint = CGPointMake(0, 0);

3.若將anchorPoint改為(1, 1),myLayer的右下角會在(100, 100)位置
1 myLayer.anchorPoint = CGPointMake(1, 1);

4.將anchorPoint改為(0, 1),myLayer的左下角會在(100, 100)位置
1 myLayer.anchorPoint = CGPointMake(0, 1);

我想,你應該已經(jīng)大概明白anchorPoint的用途了吧,它決定著CALayer身上的哪個點會在position所指定的位置上。它的x、y取值范圍都是0~1,默認值為(0.5, 0.5),因此,默認情況下,CALayer的中點會在position所指定的位置上。當anchorPoint為其他值時,以此類推。
anchorPoint是視圖的中心點,position是視圖的位置,位置會和中心點重疊。所以我們在開發(fā)中可以通過修改視圖的layer.anchorPoint或者layer.position實現(xiàn)特定的動畫效果。
下面舉個兩個??
兩份代碼,上面那個是anchorPoint為(0.5, 0.5)也就是默認情況下,下面那個是(0, 0)。

代碼如下:
self.redView.layer.anchorPoint = CGPointMake(0.5, 0.5);
[UIView animateWithDuration:3.0 animations:^{
self.redView.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
}];

代碼如下:
self.redView.layer.anchorPoint = CGPointMake(0, 0);
[UIView animateWithDuration:3.0 animations:^{
self.redView.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
}];
隱式動畫
根層與非根層:
- 每一個UIView內(nèi)部都默認關聯(lián)著一個CALayer,我們可用稱這個Layer為Root Layer(根層)
- 所有的非Root Layer,也就是手動創(chuàng)建的CALayer對象,都存在著隱式動畫
當對非Root Layer的部分屬性進行修改時,默認會自動產(chǎn)生一些動畫效果,而這些屬性稱為Animatable Properties(可動畫屬性)。
常見的幾個可動畫屬性:
bounds:用于設置CALayer的寬度和高度。修改這個屬性會產(chǎn)生縮放動畫
backgroundColor:用于設置CALayer的背景色。修改這個屬性會產(chǎn)生背景色的漸變動畫
position:用于設置CALayer的位置。修改這個屬性會產(chǎn)生平移動畫
可以通過事務關閉隱式動畫:
[CATransaction begin];
// 關閉隱式動畫
[CATransaction setDisableActions:YES];
self.myview.layer.position = CGPointMake(10, 10);
[CATransaction commit];
扯得有點遠了,我們繼續(xù)回到主題,下面正式介紹核心動畫。
Core Animation簡介
Core Animation,中文翻譯為核心動畫,它是一組非常強大的動畫處理API,使用它能做出非常炫麗的動畫效果,而且往往是事半功倍。也就是說,使用少量的代碼就可以實現(xiàn)非常強大的功能。
Core Animation可以用在Mac OS X和iOS平臺。
Core Animation的動畫執(zhí)行過程都是在后臺操作的,不會阻塞主線程。
要注意的是,Core Animation是直接作用在CALayer上的,并非UIView。
喬幫主在2007年的WWDC大會上親自為你演示Core Animation的強大:點擊查看視頻
核心動畫
如果是xcode5之前的版本,使用它需要先添加QuartzCore.framework和引入對應的框架<QuartzCore/QuartzCore.h>
開發(fā)步驟:
1.使用它需要先添加QuartzCore.framework框架和引入主頭文件<QuartzCore/QuartzCore.h>
2.初始化一個CAAnimation對象,并設置一些動畫相關屬性
3.通過調(diào)用CALayer的addAnimation:forKey:方法增加CAAnimation對象到CALayer中,這樣就能開始執(zhí)行動畫了
4.通過調(diào)用CALayer的removeAnimationForKey:方法可以停止CALayer中的動畫
**

**
CAAnimation——所有動畫對象的父類
是所有動畫對象的父類,負責控制動畫的持續(xù)時間和速度,是個抽象類,不能直接使用,應該使用它具體的子類
屬性說明:(帶*號代表來自CAMediaTiming協(xié)議的屬性)
- *duration:動畫的持續(xù)時間
- *repeatCount:重復次數(shù),無限循環(huán)可以設置HUGE_VALF或者MAXFLOAT
- *repeatDuration:重復時間
- removedOnCompletion:默認為YES,代表動畫執(zhí)行完畢后就從圖層上移除,圖形會恢復到動畫執(zhí)行前的狀態(tài)。如果想讓圖層保持顯示動畫執(zhí)行后的狀態(tài),那就設置為NO,不過還要設置fillMode為kCAFillModeForwards
- *fillMode:決定當前對象在非active時間段的行為。比如動畫開始之前或者動畫結(jié)束之后
- *beginTime:可以用來設置動畫延遲執(zhí)行時間,若想延遲2s,就設置為CACurrentMediaTime()+2,CACurrentMediaTime()為圖層的當前時間
- timingFunction:速度控制函數(shù),控制動畫運行的節(jié)奏
- delegate:動畫代理
CAAnimation——動畫填充模式
- fillMode屬性值(要想fillMode有效,最好設置removedOnCompletion = NO)
- kCAFillModeRemoved 這個是默認值,也就是說當動畫開始前和動畫結(jié)束后,動畫對layer都沒有影響,動畫結(jié)束后,layer會恢復到之前的狀態(tài)
- kCAFillModeForwards 當動畫結(jié)束后,layer會一直保持著動畫最后的狀態(tài)
- kCAFillModeBackwards 在動畫開始前,只需要將動畫加入了一個layer,layer便立即進入動畫的初始狀態(tài)并等待動畫開始。
- kCAFillModeBoth 這個其實就是上面兩個的合成.動畫加入后開始之前,layer便處于動畫初始狀態(tài),動畫結(jié)束后layer保持動畫最后的狀態(tài)
CAAnimation——速度控制函數(shù)
速度控制函數(shù)(CAMediaTimingFunction)
- kCAMediaTimingFunctionLinear(線性):勻速,給你一個相對靜態(tài)的感覺
- kCAMediaTimingFunctionEaseIn(漸進):動畫緩慢進入,然后加速離開
- kCAMediaTimingFunctionEaseOut(漸出):動畫全速進入,然后減速的到達目的地
- kCAMediaTimingFunctionEaseInEaseOut(漸進漸出):動畫緩慢的進入,中間加速,然后減速的到達目的地。這個是默認的動畫行為。
設置動畫的執(zhí)行節(jié)奏
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
CAAnimation——動畫代理方法
CAAnimation在分類中定義了代理方法,是給NSObject添加的分類,所以任何對象,成為CAAnimation的代理都可以
@interface NSObject (CAAnimationDelegate)
/* Called when the animation begins its active duration. */
動畫開始的時候調(diào)用
- (void)animationDidStart:(CAAnimation *)anim;
動畫停止的時候調(diào)用
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag;
@end
CALayer上動畫的暫停和恢復
#pragma mark 暫停CALayer的動畫
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
讓CALayer的時間停止走動
layer.speed = 0.0;
讓CALayer的時間停留在pausedTime這個時刻
layer.timeOffset = pausedTime;
}
CALayer上動畫的恢復
#pragma mark 恢復CALayer的動畫
-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = layer.timeOffset;
1. 讓CALayer的時間繼續(xù)行走
layer.speed = 1.0;
2. 取消上次記錄的停留時刻
layer.timeOffset = 0.0;
3. 取消上次設置的時間
layer.beginTime = 0.0;
4. 計算暫停的時間(這里也可以用CACurrentMediaTime()-pausedTime)
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
5. 設置相對于父坐標系的開始時間(往后退timeSincePause)
layer.beginTime = timeSincePause;
}
CAPropertyAnimation
是CAAnimation的子類,也是個抽象類,要想創(chuàng)建動畫對象,應該使用它的兩個子類:
CABasicAnimation
CAKeyframeAnimation
屬性說明:
keyPath:通過指定CALayer的一個屬性名稱為keyPath(NSString類型),并且對CALayer的這個屬性的值進行修改,達到相應的動畫效果。比如,指定@“position”為keyPath,就修改CALayer的position屬性的值,以達到平移的動畫效果
CABasicAnimation——基本動畫
基本動畫,是CAPropertyAnimation的子類
屬性說明:
keyPath:要改變的屬性名稱(傳字符串)
fromValue:keyPath相應屬性的初始值
toValue:keyPath相應屬性的結(jié)束值
動畫過程說明:
隨著動畫的進行,在長度為duration的持續(xù)時間內(nèi),keyPath相應屬性的值從fromValue漸漸地變?yōu)閠oValue
keyPath內(nèi)容是CALayer的可動畫Animatable屬性
如果fillMode=kCAFillModeForwards同時removedOnComletion=NO,那么在動畫執(zhí)行完畢后,圖層會保持顯示動畫執(zhí)行后的狀態(tài)。但在實質(zhì)上,圖層的屬性值還是動畫執(zhí)行前的初始值,并沒有真正被改變。
//創(chuàng)建動畫
CABasicAnimation *anim = [CABasicAnimation animation];;
// 設置動畫對象
keyPath決定了執(zhí)行怎樣的動畫,調(diào)用layer的哪個屬性來執(zhí)行動畫
position:平移
anim.keyPath = @"position";
// 包裝成對象
anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];;
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 300)];
anim.duration = 2.0;
// 讓圖層保持動畫執(zhí)行完畢后的狀態(tài)
// 執(zhí)行完畢以后不要刪除動畫
anim.removedOnCompletion = NO;
// 保持最新的狀態(tài)
anim.fillMode = kCAFillModeForwards;
// 添加動畫
[self.layer addAnimation:anim forKey:nil];
舉個??:

代碼如下:
//創(chuàng)建動畫對象
CABasicAnimation *anim = [CABasicAnimation animation];
//設置動畫屬性
anim.keyPath = @"position.y";
anim.toValue = @300;
//動畫提交時,會自動刪除動畫
anim.removedOnCompletion = NO;
//設置動畫最后保持狀態(tài)
anim.fillMode = kCAFillModeForwards;
//添加動畫對象
[self.redView.layer addAnimation:anim forKey:nil];
CAKeyframeAnimation——關鍵幀動畫
關鍵幀動畫,也是CAPropertyAnimation的子類,與CABasicAnimation的區(qū)別是:
CABasicAnimation只能從一個數(shù)值(fromValue)變到另一個數(shù)值(toValue),而CAKeyframeAnimation會使用一個NSArray保存這些數(shù)值
屬性說明:
values:上述的NSArray對象。里面的元素稱為“關鍵幀”(keyframe)。動畫對象會在指定的時間(duration)內(nèi),依次顯示values數(shù)組中的每一個關鍵幀
path:代表路徑可以設置一個CGPathRef、CGMutablePathRef,讓圖層按照路徑軌跡移動。path只對CALayer的
anchorPoint和position起作用。如果設置了path,那么values將被忽略
keyTimes:可以為對應的關鍵幀指定對應的時間點,其取值范圍為0到1.0,keyTimes中的每一個時間值都對應values中的每一幀。如果沒有設置keyTimes,各個關鍵幀的時間是平分的
CABasicAnimation可看做是只有2個關鍵幀的CAKeyframeAnimation
// 創(chuàng)建動畫
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];;
// 設置動畫對象
// keyPath決定了執(zhí)行怎樣的動畫,調(diào)整哪個屬性來執(zhí)行動畫
anim.keyPath = @"position";
NSValue *v1 = [NSValue valueWithCGPoint:CGPointMake(100, 0)];
NSValue *v2 = [NSValue valueWithCGPoint:CGPointMake(200, 0)];
NSValue *v3 = [NSValue valueWithCGPoint:CGPointMake(300, 0)];
NSValue *v4 = [NSValue valueWithCGPoint:CGPointMake(400, 0)];
anim.values = @[v1,v2,v3,v4];
anim.duration = 2.0;
// 讓圖層保持動畫執(zhí)行完畢后的狀態(tài)
// 狀態(tài)執(zhí)行完畢后不要刪除動畫
anim.removedOnCompletion = NO;
// 保持最新的狀態(tài)
anim.fillMode = kCAFillModeForwards;
// 添加動畫
[self.layer addAnimation:anim forKey:nil];
// 根據(jù)路徑創(chuàng)建動畫
// 創(chuàng)建動畫
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];;
anim.keyPath = @"position";
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeForwards;
anim.duration = 2.0;
// 創(chuàng)建一個路徑
CGMutablePathRef path = CGPathCreateMutable();
// 路徑的范圍
CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 200));
// 添加路徑
anim.path = path;
// 釋放路徑(帶Create的函數(shù)創(chuàng)建的對象都需要手動釋放,否則會內(nèi)存泄露)
CGPathRelease(path);
// 添加到View的layer
[self.redView.layer addAnimation:anim forKey];
舉個??:

代碼如下:
//幀動畫
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"transform.rotation";
anim.values = @[@(angle2Radio(-5)),@(angle2Radio(5)),@(angle2Radio(-5))];
anim.repeatCount = MAXFLOAT;
//自動反轉(zhuǎn)
//anim.autoreverses = YES;
[self.imageV.layer addAnimation:anim forKey:nil];
再舉個??:

代碼如下:
#import "ViewController.h"
@interface ViewController ()
/** 注釋*/
@property (nonatomic ,weak) CALayer *fistLayer;
@property (strong, nonatomic) NSMutableArray *imageArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//設置背景
self.view.layer.contents = (id)[UIImage imageNamed:@"bg"].CGImage;
CALayer *fistLayer = [CALayer layer];
fistLayer.frame = CGRectMake(100, 288, 89, 40);
//fistLayer.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:fistLayer];
self.fistLayer = fistLayer;
//fistLayer.transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
//加載圖片
NSMutableArray *imageArray = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"fish%d",i]];
[imageArray addObject:image];
}
self.imageArray = imageArray;
//添加定時器
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
//添加動畫
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(100, 200)];
[path addLineToPoint:CGPointMake(350, 200)];
[path addLineToPoint:CGPointMake(350, 500)];
[path addQuadCurveToPoint:CGPointMake(100, 200) controlPoint:CGPointMake(150, 700)];
//傳入路徑
anim.path = path.CGPath;
anim.duration = 5;
anim.repeatCount = MAXFLOAT;
anim.calculationMode = @"cubicPaced";
anim.rotationMode = @"autoReverse";
[fistLayer addAnimation:anim forKey:nil];
}
static int _imageIndex = 0;
- (void)update {
//從數(shù)組當中取出圖片
UIImage *image = self.imageArray[_imageIndex];
self.fistLayer.contents = (id)image.CGImage;
_imageIndex++;
if (_imageIndex > 9) {
_imageIndex = 0;
}
}
@end
轉(zhuǎn)場動畫——CATransition
CATransition是CAAnimation的子類,用于做轉(zhuǎn)場動畫,能夠為層提供移出屏幕和移入屏幕的動畫效果。iOS比Mac OS X的轉(zhuǎn)場動畫效果少一點
UINavigationController就是通過CATransition實現(xiàn)了將控制器的視圖推入屏幕的動畫效果
動畫屬性:(有的屬性是具備方向的,詳情看下圖)
type:動畫過渡類型
subtype:動畫過渡方向
startProgress:動畫起點(在整體動畫的百分比)
endProgress:動畫終點(在整體動畫的百分比)

CATransition *anim = [CATransition animation];
轉(zhuǎn)場類型
anim.type = @"cube";
動畫執(zhí)行時間
anim.duration = 0.5;
動畫執(zhí)行方向
anim.subtype = kCATransitionFromLeft;
添加到View的layer
[self.redView.layer addAnimation:anim forKey];
舉個??:

#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageV;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.imageV.userInteractionEnabled = YES;
//添加手勢
UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
[self.imageV addGestureRecognizer:leftSwipe];
UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
[self.imageV addGestureRecognizer:rightSwipe];
}
static int _imageIndex = 0;
- (void)swipe:(UISwipeGestureRecognizer *)swipe {
//轉(zhuǎn)場代碼與轉(zhuǎn)場動畫必須得在同一個方法當中.
NSString *dir = nil;
if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
_imageIndex++;
if (_imageIndex > 4) {
_imageIndex = 0;
}
NSString *imageName = [NSString stringWithFormat:@"%d",_imageIndex];
self.imageV.image = [UIImage imageNamed:imageName];
dir = @"fromRight";
}else if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
_imageIndex--;
if (_imageIndex < 0) {
_imageIndex = 4;
}
NSString *imageName = [NSString stringWithFormat:@"%d",_imageIndex];
self.imageV.image = [UIImage imageNamed:imageName];
dir = @"fromLeft";
}
//添加動畫
CATransition *anim = [CATransition animation];
//設置轉(zhuǎn)場類型
anim.type = @"cube";
//設置轉(zhuǎn)場的方向
anim.subtype = dir;
anim.duration = 0.5;
//動畫從哪個點開始
// anim.startProgress = 0.2;
// anim.endProgress = 0.3;
[self.imageV.layer addAnimation:anim forKey:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
CAAnimationGroup——動畫組
動畫組,是CAAnimation的子類,可以保存一組動畫對象,將CAAnimationGroup對象加入層后,組中所有動畫對象可以同時并發(fā)運行
屬性說明:
animations:用來保存一組動畫對象的NSArray
默認情況下,一組動畫對象是同時運行的,也可以通過設置動畫對象的beginTime屬性來更改動畫的開始時間
CAAnimationGroup *group = [CAAnimationGroup animation];
// 創(chuàng)建旋轉(zhuǎn)動畫對象
CABasicAnimation *retate = [CABasicAnimation animation];
// layer的旋轉(zhuǎn)屬性
retate.keyPath = @"transform.rotation";
// 角度
retate.toValue = @(M_PI);
// 創(chuàng)建縮放動畫對象
CABasicAnimation *scale = [CABasicAnimation animation];
// 縮放屬性
scale.keyPath = @"transform.scale";
// 縮放比例
scale.toValue = @(0.0);
// 添加到動畫組當中
group.animations = @[retate,scale];
// 執(zhí)行動畫時間
group.duration = 2.0;
// 執(zhí)行完以后不要刪除動畫
group.removedOnCompletion = NO;
// 保持最新的狀態(tài)
group.fillMode = kCAFillModeForwards;
[self.view.layer addAnimation:group forKey:nil];
舉個??:

代碼如下:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *redView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//移動
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"position.y";
anim.toValue = @500;
// anim.removedOnCompletion = NO;
// anim.fillMode = kCAFillModeForwards;
// [self.redView.layer addAnimation:anim forKey:nil];
//
//縮放
CABasicAnimation *anim2 = [CABasicAnimation animation];
anim2.keyPath = @"transform.scale";
anim2.toValue = @0.5;
// anim2.removedOnCompletion = NO;
// anim2.fillMode = kCAFillModeForwards;
// [self.redView.layer addAnimation:anim2 forKey:nil];
CAAnimationGroup *groupAnim = [CAAnimationGroup animation];
//會執(zhí)行數(shù)組當中每一個動畫對象
groupAnim.animations = @[anim,anim2];
groupAnim.removedOnCompletion = NO;
groupAnim.fillMode = kCAFillModeForwards;
[self.redView.layer addAnimation:groupAnim forKey:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
三大動畫:(不需要交互的時候可以選擇以下動畫)
CAAnimationGroup——動畫組
CAKeyframeAnimation——關鍵幀動畫
轉(zhuǎn)場動畫——CATransition
使用UIView動畫函數(shù)實現(xiàn)轉(zhuǎn)場動畫——單視圖
//參數(shù)說明:
duration:動畫的持續(xù)時間
view:需要進行轉(zhuǎn)場動畫的視圖
options:轉(zhuǎn)場動畫的類型
animations:將改變視圖屬性的代碼放在這個block中
completion:動畫結(jié)束后,會自動調(diào)用這個block
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
使用UIView動畫函數(shù)實現(xiàn)轉(zhuǎn)場動畫——雙視圖
參數(shù)說明:
duration:動畫的持續(xù)時間
options:轉(zhuǎn)場動畫的類型
animations:將改變視圖屬性的代碼放在這個block中
completion:動畫結(jié)束后,會自動調(diào)用這個block
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion;
轉(zhuǎn)場動畫
1.創(chuàng)建轉(zhuǎn)場動畫:[CATransition animation];
2.設置動畫屬性值
3.添加到需要專場動畫的圖層上 [ layer addAimation:animation forKer:nil];
轉(zhuǎn)場動畫的類型(NSString *type)
fade : 交叉淡化過渡
push : 新視圖把舊視圖推出去
moveIn: 新視圖移到舊視圖上面
reveal: 將舊視圖移開,顯示下面的新視圖
cube : 立方體翻滾效果
oglFlip : 上下左右翻轉(zhuǎn)效果
suckEffect : 收縮效果,如一塊布被抽走
rippleEffect: 水滴效果
pageCurl : 向上翻頁效果
pageUnCurl : 向下翻頁效果
cameraIrisHollowOpen : 相機鏡頭打開效果
cameraIrisHollowClos : 相機鏡頭關閉效果
注意:核心動畫只是修改了控件的圖形樹,換句話說就是只是修改了他的顯示,并沒有改變控件的真實位置!?。∫簿褪钦f在動畫的過程中點擊控件是不能跟用戶進行交互的,切記切記?。。‘斎?,點擊控件的起始位置是可以的。
3.幀動畫
這里講的幀動畫是指UIIMageView自帶的動畫。順帶跟大家講下怎么將一個git動態(tài)圖里面的圖片取出來,并加以顯示。
動畫屬性:
@property (nonatomic) NSTimeInterval animationDuration; // for one cycle of images. default is number of images * 1/30th of a second (i.e. 30 fps)
@property (nonatomic) NSInteger animationRepeatCount; // 0 means infinite (default is 0)
舉個??:

代碼如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSArray *imageArray = [self getImageArrayWithGIFNameWit:@"aisi"];
self.imageView.animationImages = imageArray;
self.imageView.animationDuration = 3;
self.imageView.animationRepeatCount = MAXFLOAT;
[self.imageView startAnimating];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[_imageView stopAnimating];
});
}
- (NSArray<UIImage *> *)getImageArrayWithGIFNameWit:(NSString *)imageName {
NSMutableArray *imageArray = [NSMutableArray array];
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
if (!data) {
NSLog(@"圖片不存在!");
return nil;
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
if (count <= 1) {
[imageArray addObject:[[UIImage alloc] initWithData:data]];
}else {
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
[imageArray addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
}
}
CFRelease(source);
return imageArray;
}
4.自定義轉(zhuǎn)場動畫
這部分等博主整理完成再完善,喜歡的朋友可以點擊喜歡跟進。