2018-06-13

在iOS實際開發中常用的動畫無非是以下四種:UIView動畫,核心動畫,幀動畫,自定義轉場動畫。下面我們逐個介紹。

1.UIView動畫

能實現UIView動畫的屬性

UIView動畫是iOS開發中最廉價也是最常用的動畫。

UIView動畫能夠設置的動畫屬性有:

frame

bounds

center

transform

alpha

backgroundColor

contentStretch

UIView動畫實現方式

UIView動畫實現方式有普通方式和Block方式,不過平常我們一般會直接使用Block的方式。簡單,粗暴,管用!

先說說普通方式實現動畫。

開始動畫語句:

// 第一個參數: 動畫標識// 第二個參數: 附加參數,在設置代理情況下,此參數將發送到setAnimationWillStartSelector和setAnimationDidStopSelector所指定的方法,大部分情況,設置為nil.[UIViewbeginAnimations:(nullableNSString*) context:(nullablevoid*)];

結束動畫語句:

[UIViewcommitAnimations];

動畫參數的屬性設置:

//動畫持續時間[UIViewsetAnimationDuration:(NSTimeInterval)];//動畫的代理對象 [UIViewsetAnimationDelegate:(nullableid)];//設置動畫將開始時代理對象執行的SEL[UIViewsetAnimationWillStartSelector:(nullableSEL)];//設置動畫延遲執行的時間[UIViewsetAnimationDelay:(NSTimeInterval)];//設置動畫的重復次數[UIViewsetAnimationRepeatCount:(float)];//設置動畫的曲線/*

UIViewAnimationCurve的枚舉值:

UIViewAnimationCurveEaseInOut,? ? ? ? // 慢進慢出(默認值)

UIViewAnimationCurveEaseIn,? ? ? ? ? ? // 慢進

UIViewAnimationCurveEaseOut,? ? ? ? ? // 慢出

UIViewAnimationCurveLinear? ? ? ? ? ? // 勻速

*/[UIViewsetAnimationCurve:(UIViewAnimationCurve)];//設置是否從當前狀態開始播放動畫/*假設上一個動畫正在播放,且尚未播放完畢,我們將要進行一個新的動畫:

當為YES時:動畫將從上一個動畫所在的狀態開始播放

當為NO時:動畫將從上一個動畫所指定的最終狀態開始播放(此時上一個動畫馬上結束)*/[UIViewsetAnimationBeginsFromCurrentState:YES];//設置動畫是否繼續執行相反的動畫[UIViewsetAnimationRepeatAutoreverses:(BOOL)];//是否禁用動畫效果(對象屬性依然會被改變,只是沒有動畫效果)[UIViewsetAnimationsEnabled:(BOOL)];//設置視圖的過渡效果/* 第一個參數:UIViewAnimationTransition的枚舉值如下

? ? UIViewAnimationTransitionNone,? ? ? ? ? ? ? //不使用動畫

? ? UIViewAnimationTransitionFlipFromLeft,? ? ? //從左向右旋轉翻頁

? ? UIViewAnimationTransitionFlipFromRight,? ? //從右向左旋轉翻頁

? ? UIViewAnimationTransitionCurlUp,? ? ? ? ? ? //從下往上卷曲翻頁

? ? UIViewAnimationTransitionCurlDown,? ? ? ? ? //從上往下卷曲翻頁

第二個參數:需要過渡效果的View

第三個參數:是否使用視圖緩存,YES:視圖在開始和結束時渲染一次;NO:視圖在每一幀都渲染*/[UIViewsetAnimationTransition:(UIViewAnimationTransition) forView:(nonnullUIView*) cache:(BOOL)];

下面列出三個??:

UIView動畫例子1.gif

代碼如下:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{UITouch*tuch = touches.anyObject;CGPointpoint = [tuch locationInView:self.view];? ? ? ? [UIViewbeginAnimations:@"testAnimation"context:nil];? ? [UIViewsetAnimationDuration:3.0];? ? [UIViewsetAnimationDelegate:self];//設置動畫將開始時代理對象執行的SEL[UIViewsetAnimationWillStartSelector:@selector(animationDoing)];//設置動畫延遲執行的時間[UIViewsetAnimationDelay:0];? ? ? ? [UIViewsetAnimationRepeatCount:MAXFLOAT];? ? [UIViewsetAnimationCurve:UIViewAnimationCurveLinear];//設置動畫是否繼續執行相反的動畫[UIViewsetAnimationRepeatAutoreverses:YES];self.redView.center = point;self.redView.transform =CGAffineTransformMakeScale(1.5,1.5);self.redView.transform =CGAffineTransformMakeRotation(M_PI);? ? ? ? [UIViewcommitAnimations];}

UIView動畫例子2.gif

代碼如下:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{// 轉成動畫 (flip)[UIViewbeginAnimations:@"imageViewTranslation"context:nil];? ? [UIViewsetAnimationDuration:2.0];? ? [UIViewsetAnimationDelegate:self];? ? [UIViewsetAnimationWillStartSelector:@selector(startAnimation)];? ? [UIViewsetAnimationDidStopSelector:@selector(stopAnimation)];? ? [UIViewsetAnimationRepeatCount:1.0];? ? [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];? ? [UIViewsetAnimationRepeatAutoreverses:YES];? ? [UIViewsetAnimationRepeatCount:MAXFLOAT];? ? [UIViewsetAnimationTransition:UIViewAnimationTransitionFlipFromLeftforView:self.imageView cache:YES];if(++count %2==0) {self.imageView.image = [UIImageimageNamed:@"yh_detial_ty"];? ? }else{self.imageView.image = [UIImageimageNamed:@"yh_detial_bz"];? ? }? ? [UIViewcommitAnimations];? ? }

AnimationTransitionCurlUp.gif

代碼如下:

[UIViewbeginAnimations:@"test"context:nil];? ? ? ? [UIViewsetAnimationDuration:1.0];? ? [UIViewsetAnimationRepeatCount:MAXFLOAT];? ? [UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUpforView:self.redView cache:YES];? ? ? ? [UIViewcommitAnimations];

UIView Block 動畫

ios4.0以后增加了Block動畫塊,提供了更簡潔的方式來實現動畫.日常開發中一般也是使用Block形式創建動畫。

最簡潔的Block動畫:包含時間和動畫:

[UIViewanimateWithDuration:(NSTimeInterval)//動畫持續時間animations:^{//執行的動畫}];

帶有動畫提交回調的Block動畫

[UIViewanimateWithDuration:(NSTimeInterval)//動畫持續時間animations:^{//執行的動畫}? ? ? ? ? ? ? ? completion:^(BOOLfinished) {//動畫執行提交后的操作}];

可以設置延時時間和過渡效果的Block動畫

[UIViewanimateWithDuration:(NSTimeInterval)//動畫持續時間delay:(NSTimeInterval)//動畫延遲執行的時間options:(UIViewAnimationOptions)//動畫的過渡效果animations:^{//執行的動畫}? ? ? ? ? ? ? ? completion:^(BOOLfinished) {//動畫執行提交后的操作}];

UIViewAnimationOptions的枚舉值如下,可組合使用:

UIViewAnimationOptionLayoutSubviews//進行動畫時布局子控件UIViewAnimationOptionAllowUserInteraction//進行動畫時允許用戶交互UIViewAnimationOptionBeginFromCurrentState//從當前狀態開始動畫UIViewAnimationOptionRepeat//無限重復執行動畫UIViewAnimationOptionAutoreverse//執行動畫回路UIViewAnimationOptionOverrideInheritedDuration//忽略嵌套動畫的執行時間設置UIViewAnimationOptionOverrideInheritedCurve//忽略嵌套動畫的曲線設置UIViewAnimationOptionAllowAnimatedContent//轉場:進行動畫時重繪視圖UIViewAnimationOptionShowHideTransitionViews//轉場:移除(添加和移除圖層的)動畫效果UIViewAnimationOptionOverrideInheritedOptions//不繼承父動畫設置UIViewAnimationOptionCurveEaseInOut//時間曲線,慢進慢出(默認值)UIViewAnimationOptionCurveEaseIn//時間曲線,慢進UIViewAnimationOptionCurveEaseOut//時間曲線,慢出UIViewAnimationOptionCurveLinear//時間曲線,勻速UIViewAnimationOptionTransitionNone//轉場,不使用動畫UIViewAnimationOptionTransitionFlipFromLeft//轉場,從左向右旋轉翻頁UIViewAnimationOptionTransitionFlipFromRight//轉場,從右向左旋轉翻頁UIViewAnimationOptionTransitionCurlUp//轉場,下往上卷曲翻頁UIViewAnimationOptionTransitionCurlDown//轉場,從上往下卷曲翻頁UIViewAnimationOptionTransitionCrossDissolve//轉場,交叉消失和出現UIViewAnimationOptionTransitionFlipFromTop//轉場,從上向下旋轉翻頁UIViewAnimationOptionTransitionFlipFromBottom//轉場,從下向上旋轉翻頁

Spring動畫

ios7.0以后新增了Spring動畫(IOS系統動畫大部分采用Spring Animation, 適用所有可被添加動畫效果的屬性)

[UIViewanimateWithDuration:(NSTimeInterval)//動畫持續時間delay:(NSTimeInterval)//動畫延遲執行的時間usingSpringWithDamping:(CGFloat)//震動效果,范圍0~1,數值越小震動效果越明顯initialSpringVelocity:(CGFloat)//初始速度,數值越大初始速度越快options:(UIViewAnimationOptions)//動畫的過渡效果animations:^{//執行的動畫}? ? ? ? ? ? ? ? ? completion:^(BOOLfinished) {//動畫執行提交后的操作}];

Keyframes動畫

IOS7.0后新增了關鍵幀動畫,支持屬性關鍵幀,不支持路徑關鍵幀 [UIViewanimateKeyframesWithDuration:(NSTimeInterval)//動畫持續時間delay:(NSTimeInterval)//動畫延遲執行的時間options:(UIViewKeyframeAnimationOptions)//動畫的過渡效果animations:^{//執行的關鍵幀動畫}? ? ? ? ? ? ? ? ? ? ? completion:^(BOOLfinished) {//動畫執行提交后的操作}];

UIViewKeyframeAnimationOptions的枚舉值如下,可組合使用:

UIViewAnimationOptionLayoutSubviews//進行動畫時布局子控件UIViewAnimationOptionAllowUserInteraction//進行動畫時允許用戶交互UIViewAnimationOptionBeginFromCurrentState//從當前狀態開始動畫UIViewAnimationOptionRepeat//無限重復執行動畫UIViewAnimationOptionAutoreverse//執行動畫回路UIViewAnimationOptionOverrideInheritedDuration//忽略嵌套動畫的執行時間設置UIViewAnimationOptionOverrideInheritedOptions//不繼承父動畫設置UIViewKeyframeAnimationOptionCalculationModeLinear//運算模式 :連續UIViewKeyframeAnimationOptionCalculationModeDiscrete//運算模式 :離散UIViewKeyframeAnimationOptionCalculationModePaced//運算模式 :均勻執行UIViewKeyframeAnimationOptionCalculationModeCubic//運算模式 :平滑UIViewKeyframeAnimationOptionCalculationModeCubicPaced//運算模式 :平滑均勻

各種運算模式的直觀比較如下圖:

UIViewKeyframeAnimationOptions效果對比圖.png

增加關鍵幀方法:

[UIViewaddKeyframeWithRelativeStartTime:(double)//動畫開始的時間(占總時間的比例)relativeDuration:(double)//動畫持續時間(占總時間的比例)animations:^{//執行的動畫}];

轉場動畫:

a.從舊視圖到新視圖的動畫效果

[UIViewtransitionFromView:(nonnullUIView*) toView:(nonnullUIView*) duration:(NSTimeInterval) options:(UIViewAnimationOptions) completion:^(BOOLfinished) {//動畫執行提交后的操作}];

在該動畫過程中,fromView 會從父視圖中移除,并將 toView 添加到父視圖中,注意轉場動畫的作用對象是父視圖(過渡效果體現在父視圖上)。調用該方法相當于執行下面兩句代碼:

[fromView.superview addSubview:toView];[fromView removeFromSuperview];

單個視圖的過渡效果

[UIViewtransitionWithView:(nonnullUIView*)? ? ? ? ? ? ? duration:(NSTimeInterval)? ? ? ? ? ? ? ? options:(UIViewAnimationOptions)? ? ? ? ? ? animations:^{//執行的動畫}? ? ? ? ? ? completion:^(BOOLfinished) {//動畫執行提交后的操作}];

下面依舊舉兩個??:

UIView動畫例子3.gif

代碼如下:

[UIViewanimateWithDuration:3.0animations:^{self.redView.center = point;self.redView.transform =CGAffineTransformMakeScale(1.5,1.5);self.redView.transform =CGAffineTransformMakeRotation(M_PI);? ? } completion:^(BOOLfinished) {? ? ? ? [UIViewanimateWithDuration:2.0animations:^{self.redView.frame =CGRectMake(100,100,100,100);self.redView.transform =CGAffineTransformMakeScale(1/1.5,1/1.5);self.redView.transform =CGAffineTransformMakeRotation(M_PI);? ? ? ? }];? ? }];

UIView動畫例子4.gif

代碼如下:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{self.redView.alpha =0;/*

animateWithDuration 動畫持續時間

delay 動畫延遲執行的時間

usingSpringWithDamping 震動效果,范圍0~1,數值越小震動效果越明顯

initialSpringVelocity 初始速度,數值越大初始速度越快

options 動畫的過渡效果

*/[UIViewanimateWithDuration:3.0delay:1.0usingSpringWithDamping:0.3initialSpringVelocity:1options:UIViewAnimationOptionAllowUserInteractionanimations:^{self.redView.alpha =1.0;self.redView.frame =CGRectMake(200,350,140,140);? ? } completion:^(BOOLfinished) {? ? ? ? [self.redView removeFromSuperview];? ? }];}

2.核心動畫

說道核心動畫,那就不得不先說下CALayer。

在iOS系統中,你能看得見摸得著的東西基本上都是UIView,比如一個按鈕、一個文本標簽、一個文本輸入框、一個圖標等等,這些都是UIView。

其實UIView之所以能顯示在屏幕上,完全是因為它內部的一個層。

在創建UIView對象時,UIView內部會自動創建一個層(即CALayer對象),通過UIView的layer屬性可以訪問這個層。當UIView需要顯示到屏幕上時,會調用drawRect:方法進行繪圖,并且會將所有內容繪制在自己的層上,繪圖完畢后,系統會將層拷貝到屏幕上,于是就完成了UIView的顯示。

換句話說,UIView本身不具備顯示的功能,是它內部的層才有顯示功能。

上面已經說過了,UIView之所以能夠顯示,完全是因為內部的CALayer對象。因此,通過操作這個CALayer對象,可以很方便地調整UIView的一些界面屬性,比如:陰影、圓角大小、邊框寬度和顏色等。

//下面是CALayer的一些屬性介紹//寬度和高度@propertyCGRectbounds;//位置(默認指中點,具體由anchorPoint決定)@propertyCGPointposition;//錨點(x,y的范圍都是0-1),決定了position的含義@propertyCGPointanchorPoint;//背景顏色(CGColorRef類型)@propertyCGColorRefbackgroundColor;//形變屬性@propertyCATransform3Dtransform;//邊框顏色(CGColorRef類型)@propertyCGColorRefborderColor;//邊框寬度@propertyCGFloatborderWidth;//圓角半徑@propertyCGFloatcornerRadius;//內容(比如設置為圖片CGImageRef)@property(retain)idcontents;

說明:可以通過設置contents屬性給UIView設置背景圖片,注意必須是CGImage才能顯示,我們可以在UIImage對象后面加上.CGImage直接轉換,轉換之后還需要在前面加上(id)進行強轉。

// 跨框架賦值需要進行橋接self.view.layer.contents = (__bridgeid_Nullable)([UIImageimageNamed:@"123"].CGImage);

值得注意的是,UIView的CALayer對象(層)通過layer屬性可以訪問這個層。要注意的是,這個默認的層不允許重新創建,但可以往層里面添加子層。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.創建一個CALayer,添加到控制器的view的layer中

CALayer*myLayer = [CALayerlayer];// 設置層的寬度和高度(100x100)myLayer.bounds =CGRectMake(0,0,100,100);// 設置層的位置myLayer.position =CGPointMake(100,100);// 設置層的背景顏色:紅色myLayer.backgroundColor = [UIColorredColor].CGColor;// 添加myLayer到控制器的view的layer中[self.view.layer addSublayer:myLayer];

第5行設置了myLayer的position為(100, 100),又因為anchorPoint默認是(0.5, 0.5),所以最后的效果是:myLayer的中點會在父層的(100, 100)位置

情況1.png

注意,藍色線是我自己加上去的,方便大家理解,并不是默認的顯示效果。兩條藍色線的寬度均為100。

2.若將anchorPoint改為(0, 0),myLayer的左上角會在(100, 100)位置

1 myLayer.anchorPoint = CGPointMake(0, 0);

情況2.png

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

1 myLayer.anchorPoint = CGPointMake(1, 1);

情況3.png

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

1 myLayer.anchorPoint = CGPointMake(0, 1);

情況4.png

我想,你應該已經大概明白anchorPoint的用途了吧,它決定著CALayer身上的哪個點會在position所指定的位置上。它的x、y取值范圍都是0~1,默認值為(0.5, 0.5),因此,默認情況下,CALayer的中點會在position所指定的位置上。當anchorPoint為其他值時,以此類推。

anchorPoint是視圖的中心點,position是視圖的位置,位置會和中心點重疊。所以我們在開發中可以通過修改視圖的layer.anchorPoint或者layer.position實現特定的動畫效果。

下面舉個兩個??

兩份代碼,上面那個是anchorPoint為(0.5, 0.5)也就是默認情況下,下面那個是(0, 0)。

anchorPoint(0.5,0.5).gif

代碼如下:

self.redView.layer.anchorPoint =CGPointMake(0.5,0.5);? ? [UIViewanimateWithDuration:3.0animations:^{self.redView.transform =CGAffineTransformMakeRotation(M_PI);? ? } completion:^(BOOLfinished) {? ? ? ? ? ? }];

anchorPoint(0,0).gif

代碼如下:

self.redView.layer.anchorPoint =CGPointMake(0,0);? ? [UIViewanimateWithDuration:3.0animations:^{self.redView.transform =CGAffineTransformMakeRotation(M_PI);? ? } completion:^(BOOLfinished) {? ? ? ? ? ? }];

隱式動畫

根層與非根層:

每一個UIView內部都默認關聯著一個CALayer,我們可用稱這個Layer為Root Layer(根層)

所有的非Root Layer,也就是手動創建的CALayer對象,都存在著隱式動畫

當對非Root Layer的部分屬性進行修改時,默認會自動產生一些動畫效果,而這些屬性稱為Animatable Properties(可動畫屬性)。

常見的幾個可動畫屬性:

bounds:用于設置CALayer的寬度和高度。修改這個屬性會產生縮放動畫backgroundColor:用于設置CALayer的背景色。修改這個屬性會產生背景色的漸變動畫position:用于設置CALayer的位置。修改這個屬性會產生平移動畫

可以通過事務關閉隱式動畫:

[CATransactionbegin];// 關閉隱式動畫[CATransactionsetDisableActions:YES];self.myview.layer.position =CGPointMake(10,10);[CATransactioncommit];

扯得有點遠了,我們繼續回到主題,下面正式介紹核心動畫。

Core Animation簡介

Core Animation,中文翻譯為核心動畫,它是一組非常強大的動畫處理API,使用它能做出非常炫麗的動畫效果,而且往往是事半功倍。也就是說,使用少量的代碼就可以實現非常強大的功能。

Core Animation可以用在Mac OS X和iOS平臺。

Core Animation的動畫執行過程都是在后臺操作的,不會阻塞主線程。

要注意的是,Core Animation是直接作用在CALayer上的,并非UIView。

喬幫主在2007年的WWDC大會上親自為你演示Core Animation的強大:點擊查看視頻

核心動畫

如果是xcode5之前的版本,使用它需要先添加QuartzCore.framework和引入對應的框架

開發步驟:

1.使用它需要先添加QuartzCore.framework框架和引入主頭文件

2.初始化一個CAAnimation對象,并設置一些動畫相關屬性

3.通過調用CALayer的addAnimation:forKey:方法增加CAAnimation對象到CALayer中,這樣就能開始執行動畫了

4.通過調用CALayer的removeAnimationForKey:方法可以停止CALayer中的動畫

**

CAAnimation繼承結構.png

**

CAAnimation——所有動畫對象的父類

是所有動畫對象的父類,負責控制動畫的持續時間和速度,是個抽象類,不能直接使用,應該使用它具體的子類

屬性說明:(帶*號代表來自CAMediaTiming協議的屬性)

*duration:動畫的持續時間

*repeatCount:重復次數,無限循環可以設置HUGE_VALF或者MAXFLOAT

*repeatDuration:重復時間

removedOnCompletion:默認為YES,代表動畫執行完畢后就從圖層上移除,圖形會恢復到動畫執行前的狀態。如果想讓圖層保持顯示動畫執行后的狀態,那就設置為NO,不過還要設置fillMode為kCAFillModeForwards

*fillMode:決定當前對象在非active時間段的行為。比如動畫開始之前或者動畫結束之后

*beginTime:可以用來設置動畫延遲執行時間,若想延遲2s,就設置為CACurrentMediaTime()+2,CACurrentMediaTime()為圖層的當前時間

timingFunction:速度控制函數,控制動畫運行的節奏

delegate:動畫代理

CAAnimation——動畫填充模式

fillMode屬性值(要想fillMode有效,最好設置removedOnCompletion = NO)

kCAFillModeRemoved 這個是默認值,也就是說當動畫開始前和動畫結束后,動畫對layer都沒有影響,動畫結束后,layer會恢復到之前的狀態

kCAFillModeForwards 當動畫結束后,layer會一直保持著動畫最后的狀態

kCAFillModeBackwards 在動畫開始前,只需要將動畫加入了一個layer,layer便立即進入動畫的初始狀態并等待動畫開始。

kCAFillModeBoth 這個其實就是上面兩個的合成.動畫加入后開始之前,layer便處于動畫初始狀態,動畫結束后layer保持動畫最后的狀態

CAAnimation——速度控制函數

速度控制函數(CAMediaTimingFunction)

kCAMediaTimingFunctionLinear(線性):勻速,給你一個相對靜態的感覺

kCAMediaTimingFunctionEaseIn(漸進):動畫緩慢進入,然后加速離開

kCAMediaTimingFunctionEaseOut(漸出):動畫全速進入,然后減速的到達目的地

kCAMediaTimingFunctionEaseInEaseOut(漸進漸出):動畫緩慢的進入,中間加速,然后減速的到達目的地。這個是默認的動畫行為。

設置動畫的執行節奏

anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

CAAnimation——動畫代理方法

CAAnimation在分類中定義了代理方法,是給NSObject添加的分類,所以任何對象,成為CAAnimation的代理都可以

@interfaceNSObject(CAAnimationDelegate)/* Called when the animation begins its active duration. */動畫開始的時候調用- (void)animationDidStart:(CAAnimation*)anim;動畫停止的時候調用- (void)animationDidStop:(CAAnimation*)anim finished:(BOOL)flag;@end

CALayer上動畫的暫停和恢復

#pragma mark 暫停CALayer的動畫-(void)pauseLayer:(CALayer*)layer{CFTimeIntervalpausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];? ? ? ? 讓CALayer的時間停止走動? ? layer.speed =0.0;? ? 讓CALayer的時間停留在pausedTime這個時刻? ? layer.timeOffset = pausedTime;}

CALayer上動畫的恢復

#pragma mark 恢復CALayer的動畫-(void)resumeLayer:(CALayer*)layer{CFTimeIntervalpausedTime = layer.timeOffset;1.讓CALayer的時間繼續行走? ? layer.speed =1.0;2.取消上次記錄的停留時刻? ? layer.timeOffset =0.0;3.取消上次設置的時間? ? layer.beginTime =0.0;4.計算暫停的時間(這里也可以用CACurrentMediaTime()-pausedTime)CFTimeIntervaltimeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;5.設置相對于父坐標系的開始時間(往后退timeSincePause)? ? layer.beginTime = timeSincePause;}

CAPropertyAnimation

是CAAnimation的子類,也是個抽象類,要想創建動畫對象,應該使用它的兩個子類:

CABasicAnimation

CAKeyframeAnimation

屬性說明:

keyPath:通過指定CALayer的一個屬性名稱為keyPath(NSString類型),并且對CALayer的這個屬性的值進行修改,達到相應的動畫效果。比如,指定@“position”為keyPath,就修改CALayer的position屬性的值,以達到平移的動畫效果

CABasicAnimation——基本動畫

基本動畫,是CAPropertyAnimation的子類

屬性說明:

keyPath:要改變的屬性名稱(傳字符串)

fromValue:keyPath相應屬性的初始值

toValue:keyPath相應屬性的結束值

動畫過程說明:

隨著動畫的進行,在長度為duration的持續時間內,keyPath相應屬性的值從fromValue漸漸地變為toValue

keyPath內容是CALayer的可動畫Animatable屬性

如果fillMode=kCAFillModeForwards同時removedOnComletion=NO,那么在動畫執行完畢后,圖層會保持顯示動畫執行后的狀態。但在實質上,圖層的屬性值還是動畫執行前的初始值,并沒有真正被改變。

//創建動畫CABasicAnimation*anim = [CABasicAnimationanimation];;//? ? 設置動畫對象keyPath決定了執行怎樣的動畫,調用layer的哪個屬性來執行動畫? ? ? ? ? position:平移? ? anim.keyPath =@"position";//? ? 包裝成對象anim.fromValue = [NSValuevalueWithCGPoint:CGPointMake(0,0)];;? ? anim.toValue = [NSValuevalueWithCGPoint:CGPointMake(200,300)];? ? anim.duration =2.0;//? ? 讓圖層保持動畫執行完畢后的狀態//? ? 執行完畢以后不要刪除動畫anim.removedOnCompletion =NO;//? ? 保持最新的狀態anim.fillMode = kCAFillModeForwards;//? ? 添加動畫[self.layer addAnimation:anim forKey:nil];

舉個??:

CABasicAnimation.gif

代碼如下:

//創建動畫對象CABasicAnimation*anim = [CABasicAnimationanimation];//設置動畫屬性anim.keyPath =@"position.y";? ? anim.toValue = @300;//動畫提交時,會自動刪除動畫anim.removedOnCompletion =NO;//設置動畫最后保持狀態anim.fillMode = kCAFillModeForwards;//添加動畫對象[self.redView.layer addAnimation:anim forKey:nil];

CAKeyframeAnimation——關鍵幀動畫

關鍵幀動畫,也是CAPropertyAnimation的子類,與CABasicAnimation的區別是:

CABasicAnimation只能從一個數值(fromValue)變到另一個數值(toValue),而CAKeyframeAnimation會使用一個NSArray保存這些數值

屬性說明:

values:上述的NSArray對象。里面的元素稱為“關鍵幀”(keyframe)。動畫對象會在指定的時間(duration)內,依次顯示values數組中的每一個關鍵幀

path:代表路徑可以設置一個CGPathRef、CGMutablePathRef,讓圖層按照路徑軌跡移動。path只對CALayer的

anchorPoint和position起作用。如果設置了path,那么values將被忽略

keyTimes:可以為對應的關鍵幀指定對應的時間點,其取值范圍為0到1.0,keyTimes中的每一個時間值都對應values中的每一幀。如果沒有設置keyTimes,各個關鍵幀的時間是平分的

CABasicAnimation可看做是只有2個關鍵幀的CAKeyframeAnimation

//? ? 創建動畫CAKeyframeAnimation*anim = [CAKeyframeAnimationanimation];;//? ? 設置動畫對象//? keyPath決定了執行怎樣的動畫,調整哪個屬性來執行動畫anim.keyPath =@"position";NSValue*v1 = [NSValuevalueWithCGPoint:CGPointMake(100,0)];NSValue*v2 = [NSValuevalueWithCGPoint:CGPointMake(200,0)];NSValue*v3 = [NSValuevalueWithCGPoint:CGPointMake(300,0)];NSValue*v4 = [NSValuevalueWithCGPoint:CGPointMake(400,0)];? ? anim.values = @[v1,v2,v3,v4];? anim.duration =2.0;//? ? 讓圖層保持動畫執行完畢后的狀態//? ? 狀態執行完畢后不要刪除動畫anim.removedOnCompletion =NO;//? ? 保持最新的狀態anim.fillMode = kCAFillModeForwards;//? ? 添加動畫[self.layer addAnimation:anim forKey:nil];//? 根據路徑創建動畫//? ? 創建動畫CAKeyframeAnimation*anim = [CAKeyframeAnimationanimation];;? anim.keyPath =@"position";? anim.removedOnCompletion =NO;? anim.fillMode = kCAFillModeForwards;? anim.duration =2.0;//? ? 創建一個路徑CGMutablePathRefpath =CGPathCreateMutable();//? ? 路徑的范圍CGPathAddEllipseInRect(path,NULL,CGRectMake(100,100,200,200));//? ? 添加路徑anim.path = path;//? ? 釋放路徑(帶Create的函數創建的對象都需要手動釋放,否則會內存泄露)CGPathRelease(path);//? ? 添加到View的layer[self.redView.layer addAnimation:anim forKey];

舉個??:

CAKeyframeAnimation.gif

代碼如下:

//幀動畫CAKeyframeAnimation*anim = [CAKeyframeAnimationanimation];? ? anim.keyPath =@"transform.rotation";? ? anim.values = @[@(angle2Radio(-5)),@(angle2Radio(5)),@(angle2Radio(-5))];? ? ? ? anim.repeatCount = MAXFLOAT;//自動反轉//anim.autoreverses = YES;[self.imageV.layer addAnimation:anim forKey:nil];

再舉個??:

CAKeyframeAnimation(路徑動畫).gif

代碼如下:

#import"ViewController.h"@interfaceViewController()/** 注釋*/@property(nonatomic,weak)CALayer*fistLayer;@property(strong,nonatomic)NSMutableArray*imageArray;@end@implementationViewController- (void)viewDidLoad {? ? [superviewDidLoad];//設置背景self.view.layer.contents = (id)[UIImageimageNamed:@"bg"].CGImage;CALayer*fistLayer = [CALayerlayer];? ? 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 = [NSMutableArrayarray];for(inti =0; i <10; i++) {UIImage*image = [UIImageimageNamed:[NSStringstringWithFormat:@"fish%d",i]];? ? ? ? [imageArray addObject:image];? ? }self.imageArray = imageArray;//添加定時器[NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(update) userInfo:nilrepeats:YES];//添加動畫CAKeyframeAnimation*anim = [CAKeyframeAnimationanimation];? ? anim.keyPath =@"position";UIBezierPath*path = [UIBezierPathbezierPath];? ? [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];}staticint_imageIndex =0;- (void)update {//從數組當中取出圖片UIImage*image =self.imageArray[_imageIndex];self.fistLayer.contents = (id)image.CGImage;? ? _imageIndex++;if(_imageIndex >9) {? ? ? ? _imageIndex =0;? ? }}@end

轉場動畫——CATransition

CATransition是CAAnimation的子類,用于做轉場動畫,能夠為層提供移出屏幕和移入屏幕的動畫效果。iOS比Mac OS X的轉場動畫效果少一點

UINavigationController就是通過CATransition實現了將控制器的視圖推入屏幕的動畫效果

動畫屬性:(有的屬性是具備方向的,詳情看下圖)

type:動畫過渡類型

subtype:動畫過渡方向

startProgress:動畫起點(在整體動畫的百分比)

endProgress:動畫終點(在整體動畫的百分比)

轉場動畫過渡效果.png

CATransition*anim = [CATransitionanimation];? ? 轉場類型? ? anim.type =@"cube";? ? 動畫執行時間? ? anim.duration =0.5;? ? 動畫執行方向? ? anim.subtype = kCATransitionFromLeft;? ? 添加到View的layer? ? [self.redView.layer addAnimation:anim forKey];

舉個??:

CATransition.gif

#import"ViewController.h"@interfaceViewController()@property(weak,nonatomic)IBOutletUIImageView*imageV;@end@implementationViewController- (void)viewDidLoad {? ? [superviewDidLoad];self.imageV.userInteractionEnabled =YES;//添加手勢UISwipeGestureRecognizer*leftSwipe = [[UISwipeGestureRecognizeralloc] initWithTarget:selfaction:@selector(swipe:)];? ? leftSwipe.direction =UISwipeGestureRecognizerDirectionLeft;? ? [self.imageV addGestureRecognizer:leftSwipe];UISwipeGestureRecognizer*rightSwipe = [[UISwipeGestureRecognizeralloc] initWithTarget:selfaction:@selector(swipe:)];? ? ? ? rightSwipe.direction =UISwipeGestureRecognizerDirectionRight;? ? [self.imageV addGestureRecognizer:rightSwipe];? ? }staticint_imageIndex =0;- (void)swipe:(UISwipeGestureRecognizer*)swipe {//轉場代碼與轉場動畫必須得在同一個方法當中.NSString*dir =nil;if(swipe.direction ==UISwipeGestureRecognizerDirectionLeft) {? ? ? ? ? ? ? ? _imageIndex++;if(_imageIndex >4) {? ? ? ? ? ? _imageIndex =0;? ? ? ? }NSString*imageName = [NSStringstringWithFormat:@"%d",_imageIndex];self.imageV.image = [UIImageimageNamed:imageName];? ? ? ? ? ? ? ? dir =@"fromRight";? ? }elseif(swipe.direction ==UISwipeGestureRecognizerDirectionRight) {? ? ? ? _imageIndex--;if(_imageIndex <0) {? ? ? ? ? ? _imageIndex =4;? ? ? ? }NSString*imageName = [NSStringstringWithFormat:@"%d",_imageIndex];self.imageV.image = [UIImageimageNamed:imageName];? ? ? ? ? ? ? ? dir =@"fromLeft";? ? }//添加動畫CATransition*anim = [CATransitionanimation];//設置轉場類型anim.type =@"cube";//設置轉場的方向anim.subtype = dir;? ? ? ? anim.duration =0.5;//動畫從哪個點開始//? ? anim.startProgress = 0.2;//? ? anim.endProgress = 0.3;[self.imageV.layer addAnimation:anim forKey:nil];? ? ? ? }- (void)didReceiveMemoryWarning {? ? [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end

CAAnimationGroup——動畫組

動畫組,是CAAnimation的子類,可以保存一組動畫對象,將CAAnimationGroup對象加入層后,組中所有動畫對象可以同時并發運行

屬性說明:

animations:用來保存一組動畫對象的NSArray

默認情況下,一組動畫對象是同時運行的,也可以通過設置動畫對象的beginTime屬性來更改動畫的開始時間

CAAnimationGroup*group = [CAAnimationGroupanimation];//? ? 創建旋轉動畫對象CABasicAnimation*retate = [CABasicAnimationanimation];//? ? layer的旋轉屬性retate.keyPath =@"transform.rotation";//? ? 角度retate.toValue = @(M_PI);//? ? 創建縮放動畫對象CABasicAnimation*scale = [CABasicAnimationanimation];//? ? 縮放屬性scale.keyPath =@"transform.scale";//? ? 縮放比例scale.toValue = @(0.0);//? ? 添加到動畫組當中group.animations = @[retate,scale];//? ? ? ? ? 執行動畫時間group.duration =2.0;//? ? 執行完以后不要刪除動畫group.removedOnCompletion =NO;//? ? ? ? ? 保持最新的狀態group.fillMode = kCAFillModeForwards;? ? [self.view.layer addAnimation:group forKey:nil];

舉個??:

CAAnimationGroup.gif

代碼如下:

#import"ViewController.h"@interfaceViewController()@property(weak,nonatomic)IBOutletUIView*redView;@end@implementationViewController- (void)viewDidLoad {? ? [superviewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {//移動CABasicAnimation*anim = [CABasicAnimationanimation];? ? anim.keyPath =@"position.y";? ? anim.toValue = @500;//? ? anim.removedOnCompletion = NO;//? ? anim.fillMode = kCAFillModeForwards;//? ? [self.redView.layer addAnimation:anim forKey:nil];//? ? //縮放CABasicAnimation*anim2 = [CABasicAnimationanimation];? ? anim2.keyPath =@"transform.scale";? ? anim2.toValue = @0.5;//? ? anim2.removedOnCompletion = NO;//? ? anim2.fillMode = kCAFillModeForwards;//? ? [self.redView.layer addAnimation:anim2 forKey:nil];CAAnimationGroup*groupAnim = [CAAnimationGroupanimation];//會執行數組當中每一個動畫對象groupAnim.animations = @[anim,anim2];? ? groupAnim.removedOnCompletion =NO;? ? groupAnim.fillMode = kCAFillModeForwards;? ? [self.redView.layer addAnimation:groupAnim forKey:nil];? ? }- (void)didReceiveMemoryWarning {? ? [superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end

三大動畫:(不需要交互的時候可以選擇以下動畫)

CAAnimationGroup——動畫組

CAKeyframeAnimation——關鍵幀動畫

轉場動畫——CATransition

使用UIView動畫函數實現轉場動畫——單視圖

//參數說明:duration:動畫的持續時間 view:需要進行轉場動畫的視圖 options:轉場動畫的類型 animations:將改變視圖屬性的代碼放在這個block中 completion:動畫結束后,會自動調用這個block + (void)transitionWithView:(UIView*)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void(^)(void))animations completion:(void(^)(BOOLfinished))completion;

使用UIView動畫函數實現轉場動畫——雙視圖

參數說明:duration:動畫的持續時間options:轉場動畫的類型animations:將改變視圖屬性的代碼放在這個block中completion:動畫結束后,會自動調用這個block+ (void)transitionFromView:(UIView*)fromView toView:(UIView*)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void(^)(BOOLfinished))completion;

轉場動畫

1.創建轉場動畫:[CATransition animation];

2.設置動畫屬性值

3.添加到需要專場動畫的圖層上 [ layer addAimation:animation forKer:nil];

轉場動畫的類型(NSString *type)fade : 交叉淡化過渡push : 新視圖把舊視圖推出去moveIn: 新視圖移到舊視圖上面reveal: 將舊視圖移開,顯示下面的新視圖cube : 立方體翻滾效果oglFlip : 上下左右翻轉效果suckEffect : 收縮效果,如一塊布被抽走rippleEffect: 水滴效果pageCurl : 向上翻頁效果pageUnCurl : 向下翻頁效果cameraIrisHollowOpen : 相機鏡頭打開效果cameraIrisHollowClos : 相機鏡頭關閉效果

注意:核心動畫只是修改了控件的圖形樹,換句話說就是只是修改了他的顯示,并沒有改變控件的真實位置!!!也就是說在動畫的過程中點擊控件是不能跟用戶進行交互的,切記切記!!!當然,點擊控件的起始位置是可以的。

3.幀動畫

這里講的幀動畫是指UIIMageView自帶的動畫。順帶跟大家講下怎么將一個git動態圖里面的圖片取出來,并加以顯示。

動畫屬性:

@property(nonatomic)NSTimeIntervalanimationDuration;// for one cycle of images. default is number of images * 1/30th of a second (i.e. 30 fps)@property(nonatomic)NSIntegeranimationRepeatCount;// 0 means infinite (default is 0)

舉個??:

幀動畫.gif

代碼如下:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{NSArray*imageArray = [selfgetImageArrayWithGIFNameWit:@"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 *)getImageArrayWithGIFNameWit:(NSString*)imageName {NSMutableArray*imageArray = [NSMutableArrayarray];NSString*path = [[NSBundlemainBundle] pathForResource:imageName ofType:@"gif"];NSData*data = [NSDatadataWithContentsOfFile:path];if(!data) {NSLog(@"圖片不存在!");returnnil;? ? }CGImageSourceRefsource =CGImageSourceCreateWithData((__bridgeCFDataRef)data,NULL);? ? ? ? size_t count =CGImageSourceGetCount(source);if(count <=1) {? ? ? ? [imageArray addObject:[[UIImagealloc] initWithData:data]];? ? }else{for(size_t i =0; i < count; i++) {CGImageRefimage =CGImageSourceCreateImageAtIndex(source, i,NULL);? ? ? ? ? ? ? ? ? ? ? ? [imageArray addObject:[UIImageimageWithCGImage:image scale:[UIScreenmainScreen].scale orientation:UIImageOrientationUp]];CGImageRelease(image);? ? ? ? }? ? }CFRelease(source);returnimageArray;}

作者:moxuyou

鏈接:http://www.lxweimin.com/p/9fa025c42261

來源:簡書

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,882評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,208評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,746評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,666評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,477評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,960評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,047評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,200評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,726評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,617評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,807評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,327評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,049評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,425評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,674評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,432評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,769評論 2 372

推薦閱讀更多精彩內容