Copyright © Mike's Blog
Design by Dzignine
2011年7月19日 星期二

簡單的animation

最近在開發iphone的程式 需要開場要有些動畫
在此順便記錄一下 目前試過的作法有兩個CAKeyframeAnimation , CATransition
/**
 * CAKeyframeAnimation  
 * 我覺得這個稍微複雜一點
 * 不過可以設定的比較詳細 必須自己設置 時間 路線
 * 有點像是徒手打造出有path的影格動畫
 * framework: Quartz 2D
 **/
CALayer *myLayer = [CALayer layer];

CAKeyframeAnimation *theAnimation;
theAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];  //類似keyName
theAnimation.beginTime = 0;
/**
 * 附上官網的reference 
 * void CGPathMoveToPoint (
 *  CGMutablePathRef path,
 *  const CGAffineTransform *m,
 *  CGFloat x,
 *  CGFloat y
 * );
 */        
CGMutablePathRef myPath = CGPathCreateMutable();
CGPathMoveToPoint(myPath, nil, 164, 0);
CGPathAddLineToPoint(myPath, nil, 164, 89);
CGPathAddLineToPoint(myPath, nil, 164, 57);
/** ... 類推 設定路線  **/
CGPathCloseSubpath(myPath);

theAnimation.path = myPath;
CGPathRelease(myPath);
        
/** 
 * 設定每個path需要的時間
 * 需要注意的是這裡的時間是用比例來算
 *
 */
NSMutableArray *keyTimes = [[NSMutableArray alloc] init];
[keyTimes addObject:[NSNumber numberWithFloat:0.0]];
[keyTimes addObject:[NSNumber numberWithFloat:0.425]];
[keyTimes addObject:[NSNumber numberWithFloat:1.0]];
        
theAnimation.keyTimes = keyTimes;
[theAnimation release];

theAnimation.duration = 2;
theAnimation.autoreverses = NO;
theAnimation.repeatCount = 0;
theAnimation.delegate = self;

//最後加上去就大功告成拉
[myLayer addAnimation:theAnimation forKey:@"position"];

/**
 * CATransition
 * 感覺上比較簡單使用 可以用在Layer 跟 UIView 上面
 * framework: QuartzCore.framework
 */

CATransition *theAnimation = [CATransition alloc];
theAnimation.duration = 1.0;
theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
theAnimation.type = kCATransitionPush;
theAnimation.subtype = kCATransitionFromLeft;

[song addAnimation:songAnimation forKey:@"fromLeft"];

/**
 * 如果你有附上delegate 就可在動畫結束時偵測到
 * theAnimation.delegate = self;
 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
      //do something you want
}