标签:
//创建子层 self.subLayer = [CALayer layer]; self.subLayer.bounds = CGRectMake(0, 0, 100, 100); self.subLayer.position = CGPointMake(100, 100); self.subLayer.backgroundColor = [[UIColor redColor]CGColor]; self.subLayer.cornerRadius = 50; [self.view.layer addSublayer:self.subLayer];
//创建tap手势 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Tap:)]; tap.numberOfTapsRequired = 1; tap.numberOfTouchesRequired = 1; [self.view addGestureRecognizer:tap];
#pragma mark -tap手势处理 -(void)Tap:(UITapGestureRecognizer *)sender { //获取当前的点击的位置 CGPoint location = [sender locationInView:self.view]; //创建基本动画 CABasicAnimation *basicAnimation = [[CABasicAnimation alloc]init]; basicAnimation.duration = 5.0f;
//设置动画改变的值为position basicAnimation.keyPath = @"position"; //BasicAnimation.fromValue用当前位置,不用设置 basicAnimation.toValue = [NSValue valueWithCGPoint:location]; //动画执行完,停留下来,不返回原值,需要设置下面的两个属性 basicAnimation.removedOnCompletion = NO; basicAnimation.fillMode = kCAFillModeForwards; //设置代理 basicAnimation.delegate = self; //设置一个键区分动画,将指定的动画添加到子层中 [self.subLayer addAnimation:basicAnimation forKey:@"BasicAnimation"]; //没有具体实现代理方法的情况下,subLayer虽然发生移动,但是它的真正位置并没有发生改变 //NSLog(@"%@",NSStringFromCGPoint(self.subLayer.position)); }
- (IBAction)buttonClicked:(UIButton *)sender { if (sender.tag == 0) { //动画暂停 [self animationPause]; sender.tag = 1; } else { //动画恢复 [self animationResume]; sender.tag = 0; } }
//动画暂停 -(void)animationPause { //获取当前暂停时间 //CFTimeInterval pauseTime = [self.subLayer convertTime:CACurrentMediaTime() fromLayer:nil]; CFTimeInterval pauseTime = CACurrentMediaTime(); //层的速度为0,停止动画 self.subLayer.speed = 0; //保存暂停时间,便于恢复 self.subLayer.timeOffset = pauseTime; }
//动画恢复 -(void)animationResume { //获取暂停时保存的时间 CFTimeInterval pauseTime = self.subLayer.timeOffset; self.subLayer.timeOffset = 0; //设置速度 self.subLayer.speed = 1.0; //清除开始时间 self.subLayer.beginTime = 0.0; //计算开始时间 CFTimeInterval beginTime = [self.subLayer convertTime:CACurrentMediaTime() fromLayer:nil] - pauseTime; //重设开始时间 self.subLayer.beginTime = beginTime; }
#pragma mark -动画代理的方法 //动画开始时触发的方法 -(void)animationDidStart:(CAAnimation *)anim { //开始时的当前值 //NSLog(@"animationDisStart:%@",((CABasicAnimation *)anim).fromValue); } //动画停止时触发的方法 -(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { //停止时的终点值 //NSLog(@"animationDidStop,%@",((CABasicAnimation*)anim).toValue); //将subLayer的属性值真正变为动画停止时的属性值 NSValue *toValue = ((CABasicAnimation*)anim).toValue; CGPoint point = [toValue CGPointValue]; self.subLayer.position = point; } @end
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/4886056.html