何为隐式动画
隐式动画就是直接改变layer的一些属性时,并没有作动画处理,layer会附带有动画效果,而不是直接瞬间变化,这个动画时间默认是0.25秒。
layer的哪些属性有隐式动画
区分属性是不是具有隐式动画,要看属性定义有没有“Animatable”字样。比如
/* The background color of the layer. Default value is nil. Colors
* created from tiled patterns are supported. Animatable. */
@property(nullable) CGColorRef backgroundColor;
backgroundColor属性的定义最后标明了Animatable,说明修改它的值会有默认动画效果。
怎样修改隐式动画
一、通过CATransaction
在页面上放了一个layer,通过点击button修改它的颜色
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) CALayer *colorLayer;
@property (nonatomic,strong) UIButton *changeButton;
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat kScreenWidth = [UIScreen mainScreen].bounds.size.width;
_backView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/2-100, 50, 200, 200)];
_backView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_backView];
_colorLayer = [CALayer layer];
_colorLayer.frame = CGRectMake(50, 50, 100, 100);
_colorLayer.backgroundColor = [UIColor redColor].CGColor;
_colorLayer.borderWidth = 0.5;
_colorLayer.borderColor = [UIColor blackColor].CGColor;
_colorLayer.delegate = self;
[_backView.layer addSublayer:_colorLayer];
_changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_changeButton addTarget:self action:@selector(changeColor) forControlEvents:UIControlEventTouchUpInside];
_changeButton.frame = CGRectMake(50, 160, 100, 20);
[_changeButton setTitle:@"Change Color" forState:UIControlStateNormal];
[_changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_changeButton.titleLabel.font = [UIFont systemFontOfSize:10];
_changeButton.titleLabel.textColor = [UIColor blackColor];
_changeButton.layer.cornerRadius = 5;
_changeButton.layer.borderWidth = 0.5;
_changeButton.layer.borderColor = [UIColor blackColor].CGColor;
_changeButton.backgroundColor = [UIColor whiteColor];
[_backView addSubview:_changeButton];
}
- (void)changeColor{
_colorLayer.backgroundColor = [UIColor blueColor].CGColor;]
}
为了修改隐式动画,我们对changeColor作修改
- (void)changeColor{
[CATransaction begin];
[CATransaction setAnimationDuration:2];
_colorLayer.backgroundColor = [UIColor blueColor].CGColor;
[CATransaction commit];
}
这样点击改变颜色的隐式动画的时间就被修改为2秒。
CATransaction还提供了禁用隐式动画和设置完成动作等方法。
二、通过layer的actions属性
CATransition *transition = [CATransition animation];
transition.type = @"push";
transition.subtype = @"fromLeft";
_colorLayer.actions = @{@"backgroundColor":transition};
这样在改变颜色的过程中就会附带推进的动画效果。
三、通过手动实现-actionForLayer:(CALayer )layer forKey:(NSString )event方法
_colorLayer.delegate = self;
- (nullable id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event{
CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"backgroundColor";
animation.toValue = (__bridge id)[UIColor blueColor].CGColor;
return animation;
}
UIView中的layer是没有隐式动画的
UIView关联的layer的隐式动画是被禁用的,所以如果想要通过改变view.layer的属性来实现动画是行不通的,只能通过UIView动画方法或者显式的添加动画来实现。