看了隐式动画才知道原来我们经常写的直接展示的或者跳变的东西其实都是有动画的,之所以我们没有看到是因为未指定动画类型,Core Animation提供了方法去做动画,并支持显示动画。通过Core Animation我们指定动画的类型和持续时间。
CATransaction用来管理这些事务,CATransaction没有属性或者实例方法,它只有入栈和出栈
+begin//入栈
+commit//出栈
+setAnimationDuration://这是当前动画持续时间
如何开始一次事务呢?
//开始一次事务,默认时间0.25s,可手动设置
[CATransaction begin];
//设置事务持续时间
[CATransaction setAnimationDuration:1.0];
最后要注意的是使用了CATransaction就一定要commit
[CATransaction commit];
这里commit之后才会生效,begin类似于入栈操作,commit就是出栈,不写的话点击按钮是没有人物效果的。CATransaction并不只是用来显式的改变颜色,还有其他别的运用,后面会慢慢说,有兴趣的也可以自己了解。
self.colorLayer = [CALayer layer];
self.colorLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
self.colorLayer.backgroundColor = [UIColor blueColor].CGColor;
self.colorLayer.position=CGPointMake(160, 150);
//add it to our view
[self.view.layer addSublayer:self.colorLayer];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake(0, 0, 200, 50);
btn.center=CGPointMake(160, 300);
btn.backgroundColor=[UIColor blueColor];
btn.layer.cornerRadius=5;
[btn setTitle:@"Change color" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//begin a new transaction
[CATransaction begin];
//set the animation duration to 1 second
[CATransaction setAnimationDuration:1.0];
//randomize the layer background color
CGFloat red = arc4random() / (CGFloat)INT_MAX;
CGFloat green = arc4random() / (CGFloat)INT_MAX;
CGFloat blue = arc4random() / (CGFloat)INT_MAX;
self.colorLayer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
[CATransaction commit];