关于CAAnimation的懂画执行,我们见过的组多的都是以匀速运动的,而实际上,物体的运动速度并不是匀速的,要么一直加速,要么先加速后减速等等,为了实现这一缓冲的过程,需要设置CAAnimation的timingFunction属性,它是CAMediaTimingFunction的一个对象,如果要设置隐式动画的计时函数,就设置CATransaction的+setAnimationTimingFunction: 方法。
创建CAMediaTimingFunction最简单的方式是调用+timingFunctionWithName:的构造方法,它有以下几个值:
kCAMediaTimingFunctionLinear//匀速的线性计时函数 kCAMediaTimingFunctionEaseIn//缓慢加速,然后突然停止 kCAMediaTimingFunctionEaseOut//全速开始,慢慢减速 kCAMediaTimingFunctionEaseInEaseOut//慢慢加速再慢慢减速 kCAMediaTimingFunctionDefault//也是慢慢加速再慢慢减速,但是它加速减速速度略慢
下面看下测试代码:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.colorLayer = [CALayer layer]; self.colorLayer.frame = CGRectMake(0, 0, 100, 100); self.colorLayer.position = CGPointMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height/2); self.colorLayer.backgroundColor = [UIColor redColor].CGColor; [self.view.layer addSublayer:self.colorLayer]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //configure the transaction [CATransaction begin]; [CATransaction setAnimationDuration:1.0]; [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]]; //set the position self.colorLayer.position = [[touches anyObject] locationInView:self.view]; //commit transaction [CATransaction commit]; }
在UIView中,前面有说过UIView的过度动画,它同样有以上特性,要想改变UIView的缓冲,只需要设置options的参数即可:
//跟上面的变量结尾部分相似,功能也是一样的,不再一一写出来了,请对照上面来看,唯一的不同就是没有现实默认值,为第一项 UIViewAnimationOptionCurveEaseInOut// 默认值 UIViewAnimationOptionCurveEaseIn UIViewAnimationOptionCurveEaseOut UIViewAnimationOptionCurveLinear
看测试代码:
- (void)viewDidLoad { [super viewDidLoad]; //create a red layer self.colorView = [[UIView alloc] init]; self.colorView.bounds = CGRectMake(0, 0, 100, 100); self.colorView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height/2); self.colorView.backgroundColor = [UIColor redColor]; [self.view addSubview:self.colorView]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{ //set the position self.colorView.center = [[touches anyObject] locationInView:self.view]; } completion:NULL]; }
这里只是简单的运用,想要学的更多,欢迎继续关注。