iOS动画暂停和继续

执行动画过程中暂停和继续上次动画的状态继续执行动画,需要用到layer.speed 和 layer.timeOffset, layer.beginTime.
基本做法就是记录暂停时的动画时间,然后继续动画时将开始时间设置为上次暂停的时间。下面是个旋转动画的暂停和继续。

-(void)startAnimating
{
    //先判断是否已设置动画,如果已设置则执行动画
    if([_coverImageView.layer animationForKey:@"rotatianAnimKey"]){
        //如果动画正在执行则返回,避免重复执行动画
        if (_coverImageView.layer.speed == 1) {
            //speed == 1表示动画正在执行
            return;
        }
        //让动画执行
        _coverImageView.layer.speed = 1;
        
        //取消上次设置的时间
        _coverImageView.layer.beginTime = 0;
        //获取上次动画停留的时刻
        CFTimeInterval pauseTime = _coverImageView.layer.timeOffset;
            
        //取消上次记录的停留时刻
        _coverImageView.layer.timeOffset = 0;
        
        //计算暂停的时间,设置相对于父坐标系的开始时间
        _coverImageView.layer.beginTime = [_coverImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pauseTime;
        
    }else{//没有设置动画
        
        //添加动画
        [self addAnimation];
    }
}
-(void)addAnimation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];//rotation.z
    //默认是顺时针效果,若将fromValue和toValue的值互换,则为逆时针效果
    animation.toValue =   [NSNumber numberWithFloat: M_PI *2];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = 40;//执行一周40秒
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = FLT_MAX; //如果这里想设置成一直自旋转,可以设置为FLT_MAX,
    [_coverImageView.layer addAnimation:animation forKey:@"rotatianAnimKey"];
    //添加动画之后,再让动画执行,否则可能出现动画不执行的情况
    [self startAnimating];
}

-(void)stopAnimating
{
    //如果动画已经暂停,则返回,避免重复,时间会记录错误,造成动画继续后不能连续。
    if (_coverImageView.layer.speed == 0) {
        return;
    }
    //将当前动画执行到的时间保存到layer的timeOffet中
   //一定要先获取时间再暂停动画
    CFTimeInterval pausedTime = [_coverImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //将动画暂停
    _coverImageView.layer.speed = 0;
    //记录动画暂停时间
    _coverImageView.layer.timeOffset = pausedTime;
    
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 10,526评论 5 13
  • 1 CALayer IOS SDK详解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi阅读 10,578评论 3 23
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。 1.UIView...
    请叫我周小帅阅读 8,374评论 1 23
  • Core Animation Core Animation,中文翻译为核心动画,它是一组非常强大的动画处理API,...
    45b645c5912e阅读 8,170评论 0 21
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。下面我们逐个介绍。...
    4b5cb36a2ee2阅读 2,875评论 0 0