Core Anitmation 是什么??
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self.view]; [self moveToPoint:point]; } -(void)moveToPoint:(CGPoint)point{ CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"] ; // 1.设置目的点 animation.toValue =[NSValue valueWithCGPoint:point]; // 2.设置动画时长 animation.duration =0.5; // 3.设置完成后删除动画 animation.removedOnCompletion = NO; // 4.设置模式为向前填充 animation.fillMode = kCAFillModeBoth; // 5.设置速度模式为先慢后快 animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; // 6.设置开始时长延后1秒 animation.beginTime =CACurrentMediaTime() + 1; // 7.将动画添加到Layer上开始执行 [_redview.layer addAnimation:animation forKey:nil]; }
将上述代码插入到一视图控制器中,点屏幕上点击一下看看效果~
下面看一下fillMode是干啥的
#pragma mark 暂停动画 - (void)pause { // 记录停止瞬间的时间偏移量,取出当前动画定格对应的事件 CFTimeInterval time = [_redView.layer convertTime:CACurrentMediaTime() fromLayer:nil]; // 利用图层的timeOffset记录暂停的时间偏移量 _redView.layer.timeOffset = time; NSLog(@"%f", time); // 将速度设置为0,可以停止动画 _redView.layer.speed = 0.0; } #pragma mark 继续动画 - (void)resume { // 恢复时间量 CFTimeInterval pauseTime = _redView.layer.timeOffset; // 取当前媒体时间 CFTimeInterval time = CACurrentMediaTime(); // 计算时间差值 CFTimeInterval offset = time - pauseTime; NSLog(@"%f", offset); // 设置图层动画的起始时间 _redView.layer.beginTime = offset; _redView.layer.timeOffset = 0; // 恢复速度为1 _redView.layer.speed = 1.0; } // 用户抬起手指,才会执行,通常会针对touchesMove中的处理,做一些收尾工作 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { } #pragma mark - 动画代理方法 - (void)animationDidStart:(CAAnimation *)anim { NSLog(@"动画开始 %@", NSStringFromCGPoint(_redView.center)); } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { CABasicAnimation *animation = (CABasicAnimation *)anim; // 动画结束后,修正视图的位置 CGPoint point = [animation.toValue CGPointValue]; _redView.center = point; NSLog(@"动画结束 %@ %@", NSStringFromCGPoint(_redView.center), animation.toValue); } #pragma mark - 动画方法 #pragma mark 旋转动画 - (void)rotation { CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; _redView.layer.anchorPoint = CGPointMake(1, 1); // 设置旋转角度,转360 anim.toValue = @(2 * M_PI); // 要无限循环转动,指定一个非常大的数值 // 对于无限循环的动画,需要处理动画累加的问题 anim.repeatCount = HUGE_VALF; // anim.repeatCount = MAXFLOAT; // 如果要退出到后台,再次回复的时候继续执行动画,需要设置removedOnCompletion = NO anim.removedOnCompletion = NO; anim.duration = 1.0f; [_redView.layer addAnimation:anim forKey:@"myRotation"]; } #pragma mark 缩放动画 - (void)scale { // 1. 实例化 CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; // 2. toValue anim.toValue = @(2.0); anim.repeatCount = 3; // 自动反向执行动画 anim.autoreverses = YES; anim.duration = 0.3f; [_redView.layer addAnimation:anim forKey:nil]; }
原文地址:http://www.cnblogs.com/xyzaijing/p/3855024.html