动画的暂停与恢复简单实现
在控制器的touchesBegan方法中实现动画layer动画的暂停与继续,第一次点击开始动画,以后点击实现暂停和继续。
1.创建一个imageView,给它附上一张图片
2.创建一个方法,为imageView添加一个旋转的动画效果
- (void)addAnimation{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
animation.duration = 3;
animation.repeatCount = MAXFLOAT;
animation.toValue = @(M_PI*2);
[self.imageView.layer addAnimation:animation forKey:@"rotationAnimation"];
}
3.在touchesBegan方法中控制动画的暂停或继续
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//如果当前的imageView已经添加了动画
if([self.imageView.layer animationForKey:@"rotationAnimation"]){
//如果此时的动画状态为执行状态
if(self.imageView.layer.speed){
//将当前动画执行到的时间保存到layer的timeOffet中
self.imageView.layer.timeOffset = [self.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
//将动画暂停
self.imageView.layer.speed = 0;
}else{//此时为动画暂停状态
//让动画执行
self.imageView.layer.speed = 1;
//获取上次动画停留的时刻
CFTimeInterval pauseTime = self.imageView.layer.timeOffset;
//取消上次记录的停留时刻
self.imageView.layer.timeOffset = 0;
//取消上次设置的时间
self.imageView.layer.beginTime = 0;
//计算暂停的时间,设置相对于父坐标系的开始时间
self.imageView.layer.beginTime = [self.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pauseTime;
}
}else{//没有设置动画
//添加动画
[self addAnimation];
}
}