本次简单说3中动画, 隐式动画CATransaction,显式动画CABasicAnimation and CAKeyframeAnimation.
隐式动画
显式动画
CAKeyframeAnimation
案例
这次直接附上代码, 然后在button注释不用的方法就可以;
在VC .m下
@interface ViewController (){
CALayer *_layer;
UIButton *_button;
CGMutablePathRef _path;
}
@end
@implementation ViewController
//显式动画
-(void)basicAnimation:(id)sender{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
animation.fromValue = (id) [UIColor greenColor].CGColor;
animation.toValue = (id)[UIColor blueColor].CGColor;
animation.duration = 3.0;
animation.repeatCount = 5;
[_layer addAnimation:animation forKey:@"myBasicAnimation"];
_layer.backgroundColor = [UIColor blueColor].CGColor;
}
//隐式动画
-(void)changeColo:(id)sender{
[CATransaction setAnimationDuration:3.0 ];
_layer.backgroundColor = [UIColor colorWithHue:arc4random_uniform(255)/225.0 saturation:0.5 brightness:0.5 alpha:1.0].CGColor;
}
-(void)createPath{
_path =CGPathCreateMutable();
CGFloat x = self.view.center.x;
CGFloat y = self.view.center.y;
CGFloat r = 64.0;
CGPathMoveToPoint(_path, NULL, x, y);
CGPathAddArc(_path, NULL, x, y, r, 0, M_PI, YES);
CGPathCloseSubpath(_path);
}
-(void)pathAnimation:(id)sender{
CAKeyframeAnimation *animation =[CAKeyframeAnimation animationWithKeyPath:@"position"];
[self createPath];
animation .path = _path;
animation.duration = 8.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_layer addAnimation:animation forKey:@"myKeyframeAnimation"];
}
-(void)setupUI{
_button =[UIButton buttonWithType:UIButtonTypeSystem];
[_button setTitle:@"Run Animation" forState:UIControlStateNormal];
// 注释你不用的方法.
// [_button addTarget:self action:@selector(basicAnimation:) forControlEvents:UIControlEventTouchUpInside];
// [_button addTarget:self action:@selector(changeColo:) forControlEvents:UIControlEventTouchUpInside];
[_button addTarget:self action:@selector(pathAnimation:) forControlEvents:UIControlEventTouchUpInside];
[_button sizeToFit];
_button.center = self.view.center;
[self.view addSubview:_button];
}
-(void)run{
_layer = [CALayer layer];
_layer.bounds = CGRectInset(self.view.bounds, 40, 40);
_layer.position = self .view.center;
_layer.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:_layer];
[self setupUI];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self run];
}
@end
gif
[_button addTarget:self action:@selector(basicAnimation:) forControlEvents:UIControlEventTouchUpInside];
[_button addTarget:self action:@selector(changeColo:) forControlEvents:UIControlEventTouchUpInside];
[_button addTarget:self action:@selector(pathAnimation:) forControlEvents:UIControlEventTouchUpInside];