iOS动画的暂停与恢复

动画的暂停与恢复简单实现

在控制器的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];
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值