//動畫
// ViewController.mspa
// 花瓣飄落.net
//3d
#import "ViewController.h"代理
@interface ViewController ()orm
{事務
CALayer *_layer;//建立一個圖層get
}animation
@end it
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//設置背景
UIImage *backgroundImage = [UIImage imageNamed:@"background"];
self.view.backgroundColor = [UIColor colorWithPatternImage:backgroundImage];
//自定義一個圖層(花瓣)
_layer = [[CALayer alloc]init];
_layer.bounds = CGRectMake(0, 0, 16, 30);
_layer.position = CGPointMake(50, 200);
_layer.contents = (id)[UIImage imageNamed:@"petal"].CGImage;
[self.view.layer addSublayer:_layer];
//執行動畫
[self keyFrameAnimation];
}
#pragma mark 關鍵幀動畫
- (void)keyFrameAnimation
{
//1.建立關鍵幀動畫
CAKeyframeAnimation *keyframeAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//2.設置關鍵幀
//繪製貝塞爾曲線
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, _layer.position.x, _layer.position.y);//路徑移動到起點
CGPathAddCurveToPoint(path, NULL, 160, 280, -30, 300, 50, 400);//繪製2次貝塞爾曲線
keyframeAni.path = path;//設置動畫沿路徑進行
//設置一些其它的屬性
keyframeAni.duration = 10.0;
keyframeAni.beginTime = CACurrentMediaTime() + 2;//設置延遲2秒執行
keyframeAni.autoreverses = YES;
keyframeAni.repeatCount = HUGE_VALF;
//添加動畫到圖層
[_layer addAnimation:keyframeAni forKey:@"keyFrameAnimation"];
}
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
// //獲取點擊位置
// UITouch *touch = [touches anyObject];
// CGPoint location = [touch locationInView:self.view];
//
// //1.建立動畫並指定動畫屬性
// CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
// //2.設置動畫屬性初始值和結束值
// //初始值能夠不設置,默認圖層初始位置
// basicAnimation.toValue = [NSValue valueWithCGPoint:location];
// //3.設置其餘動畫屬性
// basicAnimation.duration = 5.0;//動畫時間
// basicAnimation.repeatCount = 1;//循環次數
// basicAnimation.delegate = self;
// //記錄鼠標點擊位置,在動畫結束後使用
// [basicAnimation setValue:[NSValue valueWithCGPoint:location] forKey:@"animationLocation"];
//
// //4.添加動畫。注意key至關於給動畫命名,之後可使用此名稱獲取該動畫
// [_layer addAnimation:basicAnimation forKey:@"basicAnimation"];
//}
//
//#pragma mark 動畫代理方法
//#pragma mark 動畫結束
//-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
//{
// //開啓動畫事務
// [CATransaction begin];
// //禁用隱式動畫
// [CATransaction setDisableActions:YES];
// _layer.position = [[anim valueForKey:@"animationLocation"] CGPointValue];
// //遞交動畫事務
// [CATransaction commit];
//}
@end