美文网首页2017年开始的iOS 觉醒(5星) 升星之路
CALayer动画的开始.暂停.继续.移除

CALayer动画的开始.暂停.继续.移除

作者: 大也 | 来源:发表于2017-03-16 21:11 被阅读139次

    就最近的项目中遇到的旋转动画
    需求 1.提供图片 让图片旋转起来
    2.让动画暂停以做到更好的用户体验
    3.暂停后必须继续动画 然后再移除否则第2次做旋转时会出现动画没响应的情况

    //1.动画star
    CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        rotationAnimation.duration = 1;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = 10000;
        
        [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
    //2.动画pause
        // 将当前时间CACurrentMediaTime转换为layer上的时间, 即将parent time转换为local time
        CFTimeInterval pauseTime = [view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        
        // 设置layer的timeOffset, 在继续操作也会使用到
        view.layer.timeOffset = pauseTime;
        
        // local time与parent time的比例为0, 意味着local time暂停了
        view.layer.speed = 0;
    
    //3.动画continue
        // 时间转换
        CFTimeInterval pauseTime = view.layer.timeOffset;
        // 计算暂停时间
        CFTimeInterval timeSincePause = CACurrentMediaTime() - pauseTime;
        // 取消
        view.layer.timeOffset = 0;
        // local time相对于parent time世界的beginTime
        view.layer.beginTime = timeSincePause;
        // 继续
        view.layer.speed = 1;
    
    //4.动画remove
       //移除动画(根据key值)
        [view.layer removeAnimationForKey:@"rotationAnimation"];
    

    相关文章

      网友评论

        本文标题:CALayer动画的开始.暂停.继续.移除

        本文链接:https://www.haomeiwen.com/subject/knqsnttx.html