CoreAnimation基礎介紹、簡單使用CALayer以及多種動畫效果

CoreAnimation基礎介紹、簡單使用CALayer以及多種動畫效果

發佈於:2013-05-22 15:50閱讀數:5071

Core Animation可以翻譯爲核心動畫,它爲圖形渲染和動畫提供了基礎。使用核心動畫,你只需要設置一些參數比如起點和終點,剩下的幀核心動畫爲你自動完成。核心動畫使用硬件加速,不用消耗

“”

閱讀器

CoreAnimation iOS

2

轉自榮芳志的博客:

Core Animation之基礎介紹

 Core Animation可以翻譯爲核心動畫,它爲圖形渲染和動畫提供了基礎。使用核心動畫,你只需要設置一些參數比如起點和終點,剩下的幀核心動畫爲你自動完 成。核心動畫使用硬件加速,不用消耗cpu資源。其實平時咱們開發的iOS應用都在有意無意的使用了核心動畫。動畫不會替代View,而是和View一起 提供更好的性能。Core Animation通過緩存view上的內容到bitmap,這樣bitmap就可以直接在圖形硬件上操作。從而提高了性能。

核心動畫所在的位置:

 

1、關於層類

LayerClasses是core animation的基礎。Layer Classes提供了一個抽象的概念,這個概念對於那些使用NSview和UIview的開發者來說是很熟悉的。基礎層是由CAlayer類提供的,CAlayer是所有CoreAnimation層的父類。   

同一個視圖類的實例一樣,一個CAlayer實例也有一個單獨的superlayer和上面所有的子層(sublayers),它創建了一個有 層次結構的層,我們稱之爲layer tree。layers的繪製就像views一樣是從後向前繪製的,繪製的時候我們要指定其相對與他們的superlayer的集合形狀,同時還需要創建 一個局部的座標系。layers可以做一些更復雜的操作,例如rotate(旋轉),skew(傾斜),scale(放縮),和project the layer content(層的投影)。   

 

圖層的內容提供:

(1)直接設置層的content屬性到一個coregraphics圖,或者通過delegation來設置

(2)提供一個代理直接繪製到CoreGraphics image context(核心圖形的上下文)

(3)設置任意數量的所有層共有的可視的風格屬性。例如:backgroundColor(背景色),opacity(透明度)和masking(遮罩)。max os x應用通過使用coreimage filters來達到這種可視化的屬性。

(4)子類化CAlayer,同時在更多的封裝方式中完成上面的任意技術。 

 

 1.1 CALayer的子類和他們的使用場景

Class

Usage

CAEmitterLayer

Used to implement a Core Animation–based particle emitter system. The emitter layer object controls the generation of the particles and their origin.

CAGradientLayer

Used to draw a color gradient that fills the shape of the layer (within the bounds of any rounded corners).

CAEAGLLayer/CAOpenGLLayer

Used to set up the backing store and context needed to draw using OpenGL ES (iOS) or OpenGL (OS X).

CAReplicatorLayer

Used when you want to make copies of one or more sublayers automatically. The replicator makes the copies for you and uses the properties you specify to alter the appearance or attributes of the copies.

CAScrollLayer

Used to manage a large scrollable area composed of multiple sublayers.

CAShapeLayer

Used to draw a cubic Bezier spline. Shape layers are advantageous for drawing path-based shapes because they always result in a crisp path, as opposed to a path you draw into a layer’s backing store, which would not look as good when scaled. However, the crisp results do involve rendering the shape on the main thread and caching the results.

CATextLayer

Used to render a plain or attributed string of text.

CATiledLayer

Used to manage a large image that can be divided into smaller tiles and rendered individually with support for zooming in and out of the content.

CATransformLayer

Used to render a true 3D layer hierarchy, rather than the flattened layer hierarchy implemented by other layer classes.

QCCompositionLayer

Used to render a Quartz Composer composition. (OS X only)

1.2 anchorPoint position

anchorPoint又稱錨點,錨點對動畫是有很大影響的。下圖描述了基於錨點的三個示例值:

 

1.3圖層的 frameboundsposition anchorPoint 關係如下圖所示

在該示例中,anchorPoint默認值爲(0.5,0.5),位於圖層的中心點。圖層的 position 值爲(100.0,100.0),bounds爲(0.0,0.0,120,80.0)。通過計算得到圖層的 frame爲(40.0,60.0,120.0,80.0)。

 

如果你新創建一個圖層,則只有設置圖層的frame 爲(40.0,60.0,120.0,80.0),相應的position 屬性值將會自動設置爲(100.0,100.0),而bounds 會自動設置爲 (0.0,0.0,120.0,80.0)。下圖顯示一個圖層具有相同的 frame(如上圖),但是在該圖中它的anchorPoint 屬性值被設置爲(0.0,0.0),位於圖層的左下角位置。

圖層的frame 值同樣爲(40.0,60.0,120.0,80.0),bounds 的值不變,但是圖層的position 值已經改變爲(40.0,60.0)。

 

2、關於動畫類

核心動畫的動畫類使用基本的動畫和關鍵幀動畫把圖層的內容和選取的屬性動畫的顯示出來。所有核心動畫的動畫類都是從 CAAnimation 類繼承而來。

 

CAAnimation實現了 CAMediaTiming 協議,提供了動畫的持續時間,速度,和重複計數。 CAAnimation 也實現了CAAction 協議。該協議爲圖層觸發一個動畫動作提供了提供標準化響應。動畫類同時定義了一個使用貝塞爾曲線來描述動畫改變的時間函數。例如,一個勻速時間函數(linear timing function)在動畫的整個生命週期裏面一直保持速度不變,而漸緩時間函數(ease-out timing function)則在動畫接近其生命週期的時候減慢速度。核心動畫額外提供了一系列抽象的和細化的動畫類,比如:CATransition提供了一個圖層變化的過渡效果,它能影響圖層的整個內容。 動畫進行的時候淡入淡出(fade)、推(push)、顯露(reveal)圖層的內容。這些過渡效 果可以擴展到你自己定製的Core Image 濾鏡。CAAnimationGroup允許一系列動畫效果組合在一起,並行顯示動畫。

 

2.1動畫類

 CAPropertyAnimation:是一個抽象的子類,它支持動畫的顯示圖層的關鍵路徑中指定的屬性一般不直接使用,而是使用它的子類,CABasicAnimation,CAKeyframeAnimation. 在它的子類裏修改屬性來運行動畫。

CABasicAnimation: 簡單的爲圖層的屬性提供修改。 很多圖層的屬性修改默認會執行這個動畫類。比如大小,透明度,顏色等屬性

 CAKeyframeAnimation: 支持關鍵幀動畫,你可以指定的圖層屬性的關鍵路徑動畫,包括動畫的每個階段的價值,以及關鍵幀時間和計時功能的一系列值。在 動畫運行是,每個值被特定的插入值替代。核心動畫 和Cocoa Animation 同時使用這些動畫類。

 

2.2 如何使用多個動畫效果疊加

在執行動畫的過程中需要同時修改position,alpha,frame等屬性,使用CAAnimationGroup可以將三個動畫合成一起執行:

 

1.  CAAnimationGroup *animGroup = [CAAnimationGroup animation];  

2.  animGroup.animations = [NSArray arrayWithObjects:moveAnim,scaleAnim,opacityAnim, nil]; 

3.  animGroup.duration = 1; 

4.  [view.layer addAnimation:animGroup forKey:nil]; 

 

2.3事務管理類  

  圖層的動畫屬性的每一個修改必然是事務的一個部分。CATransaction 是核心動畫裏面負責協調多個動畫原子更新顯示操作。事務支持嵌套使用。 

 

2.4 Core Animation類的繼承關係圖 

 

 

 

Core Animation之簡單使用CALayer

 

1、什麼是CALayer

CALayer是個簡單的類,它是用來在屏幕上顯示內容展示的矩形區域。 靠,這是不描述UIView的話嗎?其實他們是有區別的。每個UIView都有一個根CALayer,UIView在這個layer上描繪東西。

 

那怎麼訪問這個layer呢,很簡單:

1.  CALayer *myLayer = myView.layer; 

 

CALayer有這麼些屬性,可以設置改變層的顯示:

 

1.層的大小和位置

2.層的背景顏色

3.層的內容(圖像,coregraphics)

4.層的的圓角,半徑

5.層的陰影設置

等等....

 

2、開始

新建項目默認的模版裏是QuartzCore庫的,先添加它,才能使用CALayer。

 

小試牛刀看看。

設置層的背景顏色,層的設置圓角半徑爲20

 

1.  #import <QuartzCore/QuartzCore.h> 

2.    

3.  // Uncomment viewDidLoad and add the following lines 

4.  self.view.layer.backgroundColor = [UIColor orangeColor].CGColor; 

5.  self.view.layer.cornerRadius = 20.0; 

 

3、層和子層

獲取一個新CALayer的實例

1.  CALayer *sublayer = [CALayer layer]; 

 

設置layler的屬性,下面分別是:

設置背景色,

陰影的偏差值,

陰影的半徑,

陰影的顏色,

陰影的透明度,

子層的freme值。

然後把新的層add到view的層裏。

1.  CALayer *sublayer = [CALayer layer]; 

2.      sublayer.backgroundColor = [UIColor purpleColor].CGColor; 

3.      sublayer.shadowOffset = CGSizeMake(0, 3); 

4.      sublayer.shadowRadius = 5.0; 

5.      sublayer.shadowColor = [UIColor blackColor].CGColor; 

6.      sublayer.shadowOpacity = 0.8; 

7.      sublayer.frame = CGRectMake(30, 30, 128, 192); 

8.      [self.view.layer addSublayer:sublayer]; 

效果如下:

4、添加圖片內容和層的圓角

 

主要內容有:

新建imagelayer放置圖片

設置圓角半徑cornerRadius

設置層的內容contents爲圖片

邊界遮罩masksToBounds

 

1.  CALayer *sublayer = [CALayer layer]; 

2.  sublayer.backgroundColor = [UIColor purpleColor].CGColor; 

3.  sublayer.shadowOffset = CGSizeMake(0, 3); 

4.  sublayer.shadowRadius = 5.0; 

5.  sublayer.shadowColor = [UIColor blackColor].CGColor; 

6.  sublayer.shadowOpacity = 0.8; 

7.  sublayer.frame = CGRectMake(30, 30, 128, 192); 

8.  sublayer.borderColor = [UIColor blackColor].CGColor; 

9.  sublayer.borderWidth = 2.0; 

10.sublayer.cornerRadius = 10.0; 

11.[self.view.layer addSublayer:sublayer]; 

12. 

13.CALayer *imageLayer = [CALayer layer]; 

14.imageLayer.frame = sublayer.bounds; 

15.imageLayer.cornerRadius = 10.0; 

16.imageLayer.contents = (id)[UIImage imageNamed:@"snaguosha.png"].CGImage; 

17.imageLayer.masksToBounds = YES; 

18.[sublayer addSublayer:imageLayer]; 

效果:

 

有圓角就是好看很多。

 

5、自定義繪畫內容到圖層

如果不想使用圖片內容,而是想用Core Graphics繪製內容到層上的話也簡單。

這裏主要靠viewController類實現一個drawLayer:inContext方法,並把它設置成layer的代理。代碼如下:

 

1.  static inline double radians (double degrees) { return degrees * M_PI/180; } 

2.   

3.  void MyDrawColoredPattern (void *info, CGContextRef context) { 

4.       

5.      CGColorRef dotColor = [UIColor colorWithHue:0 saturation:0 brightness:0.07 alpha:1.0].CGColor; 

6.      CGColorRef shadowColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.1].CGColor; 

7.       

8.      CGContextSetFillColorWithColor(context, dotColor); 

9.      CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 1, shadowColor); 

10.     

11.    CGContextAddArc(context, 3, 3, 4, 0, radians(360), 0); 

12.    CGContextFillPath(context); 

13.     

14.    CGContextAddArc(context, 16, 16, 4, 0, radians(360), 0); 

15.    CGContextFillPath(context); 

16.     

17.} 

18. 

19.- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { 

20.     

21.    CGColorRef bgColor = [UIColor colorWithHue:0 saturation:0 brightness:0.15 alpha:1.0].CGColor; 

22.    CGContextSetFillColorWithColor(context, bgColor); 

23.    CGContextFillRect(context, layer.bounds); 

24.     

25.    static const CGPatternCallbacks callbacks = { 0, &MyDrawColoredPattern, NULL }; 

26.     

27.    CGContextSaveGState(context); 

28.    CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); 

29.    CGContextSetFillColorSpace(context, patternSpace); 

30.    CGColorSpaceRelease(patternSpace); 

31.     

32.    CGPatternRef pattern = CGPatternCreate(NULL, 

33.                                           layer.bounds, 

34.                                           CGAffineTransformIdentity, 

35.                                           24, 

36.                                           24, 

37.                                           kCGPatternTilingConstantSpacing, 

38.                                           true, 

39.                                           &callbacks); 

40.    CGFloat alpha = 1.0; 

41.    CGContextSetFillPattern(context, pattern, &alpha); 

42.    CGPatternRelease(pattern); 

43.    CGContextFillRect(context, layer.bounds); 

44.    CGContextRestoreGState(context); 

45.} 

 

在viewController中加入:

1.  static inline double radians (double degrees) { return degrees * M_PI/180; } 

2.   

3.  void MyDrawColoredPattern (void *info, CGContextRef context) { 

4.       

5.      CGColorRef dotColor = [UIColor colorWithHue:0 saturation:0 brightness:0.07 alpha:1.0].CGColor; 

6.      CGColorRef shadowColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.1].CGColor; 

7.       

8.      CGContextSetFillColorWithColor(context, dotColor); 

9.      CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 1, shadowColor); 

10.     

11.    CGContextAddArc(context, 3, 3, 4, 0, radians(360), 0); 

12.    CGContextFillPath(context); 

13.     

14.    CGContextAddArc(context, 16, 16, 4, 0, radians(360), 0); 

15.    CGContextFillPath(context); 

16.     

17.} 

18. 

19.- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { 

20.     

21.    CGColorRef bgColor = [UIColor colorWithHue:0 saturation:0 brightness:0.15 alpha:1.0].CGColor; 

22.    CGContextSetFillColorWithColor(context, bgColor); 

23.    CGContextFillRect(context, layer.bounds); 

24.     

25.    static const CGPatternCallbacks callbacks = { 0, &MyDrawColoredPattern, NULL }; 

26.     

27.    CGContextSaveGState(context); 

28.    CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); 

29.    CGContextSetFillColorSpace(context, patternSpace); 

30.    CGColorSpaceRelease(patternSpace); 

31.     

32.    CGPatternRef pattern = CGPatternCreate(NULL, 

33.                                           layer.bounds, 

34.                                           CGAffineTransformIdentity, 

35.                                           24, 

36.                                           24, 

37.                                           kCGPatternTilingConstantSpacing, 

38.                                           true, 

39.                                           &callbacks); 

40.    CGFloat alpha = 1.0; 

41.    CGContextSetFillPattern(context, pattern, &alpha); 

42.    CGPatternRelease(pattern); 

43.    CGContextFillRect(context, layer.bounds); 

44.    CGContextRestoreGState(context); 

45.} 

這樣,CoreGraphics繪製了一個有質地的圖像到customDrawn層上,這個繪製教程請參考:Core Graphics 101: Patterns http://www.raywenderlich.com/33496/core-graphics-tutorial-patterns

 

咱們看下這很酷的效果:

 

這個是不是像mac電腦上按下F12鍵時出來的背景。

 

本篇例子代碼:http://download.csdn.net/detail/totogo2010/5083326

參考:http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Core Animation之多種動畫效果

 

前面介紹了CoreAnimation基礎知識,還有CALayer的簡單使用,最終還是有要動畫的滴,這裏列出幾個動畫效果,參考下能加深對CoreAnimation的認識和理解。

 

1、把圖片移到右下角變小透明

使用CAAnimationGroup疊加動畫效果,就是下面按鈕《把圖片移到右下角變小透明》描述的效果:

上面三個圖是動畫的三個狀態,實現代碼如下:

 

1.  - (void)viewDidLoad 

2.  { 

3.      [super viewDidLoad]; 

4.      self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snaguosha.png"]]; 

5.      self.imageView.frame = CGRectMake(10, 10, 128, 192); 

6.      [self.view addSubview:self.imageView]; 

7.   } 

 

1.  - (IBAction)tranAction:(id)sender { 

2.      CGPoint fromPoint = self.imageView.center; 

3.       

4.      //路徑曲線 

5.      UIBezierPath *movePath = [UIBezierPath bezierPath]; 

6.      [movePath moveToPoint:fromPoint]; 

7.      CGPoint toPoint = CGPointMake(300, 460); 

8.      [movePath addQuadCurveToPoint:toPoint 

9.                       controlPoint:CGPointMake(300,0)]; 

10.    //關鍵幀 

11.    CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 

12.    moveAnim.path = movePath.CGPath; 

13.    moveAnim.removedOnCompletion = YES; 

14.     

15.    //旋轉變化 

16.    CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"]; 

17.    scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity]; 

18.    //x,y軸縮小到0.1,Z 軸不變 

19.    scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]; 

20.    scaleAnim.removedOnCompletion = YES; 

21.     

22.    //透明度變化 

23.    CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"alpha"]; 

24.    opacityAnim.fromValue = [NSNumber numberWithFloat:1.0]; 

25.    opacityAnim.toValue = [NSNumber numberWithFloat:0.1]; 

26.    opacityAnim.removedOnCompletion = YES; 

27.     

28.    //關鍵幀,旋轉,透明度組合起來執行 

29.    CAAnimationGroup *animGroup = [CAAnimationGroup animation]; 

30.    animGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim,opacityAnim, nil]; 

31.    animGroup.duration = 1; 

32.    [self.imageView.layer addAnimation:animGroup forKey:nil]; 

33.} 

代碼解析:上面關鍵幀設置了動畫的路徑,scaleAnim設置了縮小,opacityAnim設置了透明度的變化。把三個動畫組合到:animGroup。

 

在把animGroup添加到imageView.layer層的動畫裏。於是動畫效果就有了。

 

2、旋轉並向右移動

1.  - (IBAction)RightRotateAction:(id)sender { 

2.      CGPoint fromPoint = self.imageView.center; 

3.      UIBezierPath *movePath = [UIBezierPath bezierPath]; 

4.      [movePath moveToPoint:fromPoint]; 

5.      CGPoint toPoint = CGPointMake(fromPoint.x +100 , fromPoint.y ) ; 

6.      [movePath addLineToPoint:toPoint]; 

7.       

8.      CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 

9.      moveAnim.path = movePath.CGPath; 

10.     

11.    CABasicAnimation *TransformAnim = [CABasicAnimation animationWithKeyPath:@"transform"]; 

12.    TransformAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity]; 

13.     

14.    //沿Z軸旋轉 

15.    TransformAnim.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI,0,0,1)]; 

16.     

17.    //沿Y軸旋轉 

18.  //   scaleAnim.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI,0,1.0,0)]; 

19.     

20.    //沿X軸旋轉 

21.//     TransformAnim.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI,1.0,0,0)]; 

22.    TransformAnim.cumulative = YES; 

23.    TransformAnim.duration =3; 

24.    //旋轉2遍,360度 

25.    TransformAnim.repeatCount =2; 

26.    self.imageView.center = toPoint; 

27.    TransformAnim.removedOnCompletion = YES; 

28.    CAAnimationGroup *animGroup = [CAAnimationGroup animation]; 

29.    animGroup.animations = [NSArray arrayWithObjects:moveAnim, TransformAnim, nil]; 

30.    animGroup.duration = 6; 

31.     

32.    [self.imageView.layer addAnimation:animGroup forKey:nil]; 

33.} 

代碼解析:可能你沒注意到,CATransform3DMakeRotation,這返回的是旋轉的值。上面的動畫效果裏返回的是CATransform3DMakeScale縮放的值。

 

向右移動是因爲關鍵幀使用了路徑爲直線的路徑。

 

3、旋轉並消除邊緣鋸齒

 

1.  - (IBAction)Rotate360Action:(id)sender { 

2.      //圖片旋轉360度 

3.      CABasicAnimation *animation = [ CABasicAnimation 

4.                                     animationWithKeyPath: @"transform" ]; 

5.      animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity]; 

6.       

7.      //圍繞Z軸旋轉,垂直與屏幕 

8.      animation.toValue = [ NSValue valueWithCATransform3D: 

9.                           CATransform3DMakeRotation(M_PI, 0, 0, 1.0) ]; 

10.    animation.duration = 3; 

11.    //旋轉效果累計,先轉180度,接着再旋轉180度,從而實現360旋轉 

12.    animation.cumulative = YES; 

13.    animation.repeatCount = 2; 

14.     

15.    //在圖片邊緣添加一個像素的透明區域,去圖片鋸齒 

16.    CGRect imageRrect = CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height); 

17.    UIGraphicsBeginImageContext(imageRrect.size); 

18.    [self.imageView.image drawInRect:CGRectMake(1,1,self.imageView.frame.size.width-2,self.imageView.frame.size.height-2)]; 

19.    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 

20.    UIGraphicsEndImageContext(); 

21.     

22.    [self.imageView.layer addAnimation:animation forKey:nil]; 

23.} 

如果你仔細觀察,會看到第二個動畫裏在旋轉時,圖片邊緣是有鋸齒的,如何消除呢?在圖片邊緣添加一個像素的透明區域,去圖片鋸齒。

 

UIGraphicsBeginImageContext開始圖片內容。

UIGraphicsGetImageFromCurrentImageContext獲取當前內容作爲圖片。

UIGraphicsEndImageContext結束。是和UIGraphicsBeginImageContext配套使用的。

 

4、喫豆人動畫

這個有點複雜,首先說下實現的步驟:

畫一個喫豆人開口的路徑:pacmanOpenPath

畫一個喫豆人閉口的路徑:pacmanClosedPath

新建一個閉口的喫豆人頭的層:shapeLayer

 

把開口和閉口路徑設置成CABasicAnimation*chompAnimation動畫的起點和終點,這樣循環就能出現咬牙的動畫了。

 

最後設置一個路徑爲關鍵幀,讓喫豆人在這條路徑上行動。

 

代碼如下:

1.  - (void)animationInit 

2.  { 

3.      self.view.backgroundColor = [UIColor blackColor]; 

4.       

5.      CGFloat radius = 30.0f; 

6.      CGFloat diameter = radius * 2; 

7.      CGPoint arcCenter = CGPointMake(radius, radius); 

8.      // Create a UIBezierPath for Pacman's open state 

9.      pacmanOpenPath = [UIBezierPath bezierPathWithArcCenter:arcCenter 

10.                                                    radius:radius 

11.                                                startAngle:DEGREES_TO_RADIANS(35) 

12.                                                  endAngle:DEGREES_TO_RADIANS(315) 

13.                                                 clockwise:YES]; 

14.     

15.    [pacmanOpenPath addLineToPoint:arcCenter]; 

16.    [pacmanOpenPath closePath]; 

17.     

18.    // Create a UIBezierPath for Pacman's close state 

19.    pacmanClosedPath = [UIBezierPath bezierPathWithArcCenter:arcCenter 

20.                                                      radius:radius 

21.                                                  startAngle:DEGREES_TO_RADIANS(1) 

22.                                                    endAngle:DEGREES_TO_RADIANS(359) 

23.                                                   clockwise:YES]; 

24.    [pacmanClosedPath addLineToPoint:arcCenter]; 

25.    [pacmanClosedPath closePath]; 

26.     

27.    // Create a CAShapeLayer for Pacman, fill with yellow 

28.    shapeLayer = [CAShapeLayer layer]; 

29.    shapeLayer.fillColor = [UIColor yellowColor].CGColor; 

30.    shapeLayer.path = pacmanClosedPath.CGPath; 

31.    shapeLayer.strokeColor = [UIColor grayColor].CGColor; 

32.    shapeLayer.lineWidth = 1.0f; 

33.    shapeLayer.bounds = CGRectMake(0, 0, diameter, diameter); 

34.    shapeLayer.position = CGPointMake(-40, -100); 

35.    [self.view.layer addSublayer:shapeLayer]; 

36.     

37.    SEL startSelector = @selector(startAnimation); 

38.    UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:startSelector]; 

39.    [self.view addGestureRecognizer:recognizer]; 

40.} 

 

1.  - (void)startAnimation { 

2.      // 創建咬牙動畫 

3.      CABasicAnimation *chompAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; 

4.      chompAnimation.duration = 0.25; 

5.      chompAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 

6.      chompAnimation.repeatCount = HUGE_VALF; 

7.      chompAnimation.autoreverses = YES; 

8.      // Animate between the two path values 

9.      chompAnimation.fromValue = (id)pacmanClosedPath.CGPath; 

10.    chompAnimation.toValue = (id)pacmanOpenPath.CGPath; 

11.    [shapeLayer addAnimation:chompAnimation forKey:@"chompAnimation"]; 

12.     

13.    // Create digital '2'-shaped path 

14.     

15.    UIBezierPath *path = [UIBezierPath bezierPath]; 

16.    [path moveToPoint:CGPointMake(0, 100)]; 

17.    [path addLineToPoint:CGPointMake(300, 100)]; 

18.    [path addLineToPoint:CGPointMake(300, 200)]; 

19.    [path addLineToPoint:CGPointMake(0, 200)]; 

20.    [path addLineToPoint:CGPointMake(0, 300)]; 

21.    [path addLineToPoint:CGPointMake(300, 300)]; 

22.     

23.    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; 

24.    moveAnimation.path = path.CGPath; 

25.    moveAnimation.duration = 8.0f; 

26.    // Setting the rotation mode ensures Pacman's mouth is always forward.  This is a very convenient CA feature. 

27.    moveAnimation.rotationMode = kCAAnimationRotateAuto; 

28.    [shapeLayer addAnimation:moveAnimation forKey:@"moveAnimation"]; 

29.} 

 

1.  - (void)viewDidLoad 

2.  { 

3.      [super viewDidLoad]; 

4.      [self animationInit]; 

5.  } 

還需要添加一個宏:

#defineDEGREES_TO_RADIANS(x) (3.14159265358979323846 * x / 180.0)    計算角度轉換

 

添加了個手勢,點一下屏幕,喫豆人就動起來了。效果:

本篇例子代碼:代碼

 

來源:榮芳志的博客

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章