美文网首页
speed(CAMediaTiming)控制动画暂停和结束

speed(CAMediaTiming)控制动画暂停和结束

作者: 淘代码者 | 来源:发表于2017-08-18 15:23 被阅读0次
    QQ20170818-151734.gif
    //
    //  ViewController.m
    //  MediaTiming
    //
    //  Created by apple on 17/8/18.
    //  Copyright © 2017年 Wang. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    @property (nonatomic, strong) CALayer *layer;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        CALayer *layer = [CALayer layer];
        layer.backgroundColor = [UIColor purpleColor].CGColor;
        layer.frame = CGRectMake(0, 0, 100, 100);
        [self.view.layer addSublayer:layer];
        self.layer = layer;
        
        CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
        basicAnimation.duration = 4.f;
        basicAnimation.repeatCount = HUGE;
        basicAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(50, 400)];
        [layer addAnimation:basicAnimation forKey:nil];
    }
    
    - (void) pauseLayer: (CALayer *) theLayer
    {
        CFTimeInterval mediaTime = CACurrentMediaTime();
        CFTimeInterval pausedTime = [theLayer convertTime: mediaTime fromLayer: nil];
        theLayer.speed = 0.0;
        theLayer.timeOffset = pausedTime;
    }
    
    //-----------------------------------------------------------------------------
    
    - (void) removePauseForLayer: (CALayer *) theLayer;
    {
        theLayer.speed = 1.0;
        theLayer.timeOffset = 0.0;
        theLayer.beginTime = 0.0;
    }
    
    //-----------------------------------------------------------------------------
    
    - (void) resumeLayer: (CALayer *) theLayer;
    {
        CFTimeInterval pausedTime = [theLayer timeOffset];
        [self removePauseForLayer: theLayer];
        CFTimeInterval mediaTime = CACurrentMediaTime();
        CFTimeInterval timeSincePause =
        [theLayer convertTime: mediaTime fromLayer: nil] - pausedTime;
        theLayer.beginTime = timeSincePause;
    }
    
    - (IBAction)pauseClick:(UIButton *)sender {
        [self pauseLayer:self.layer];
        
    }
    
    - (IBAction)resumeClick:(UIButton *)sender {
        [self resumeLayer:self.layer];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    @end
    

    参考:How To Pause & Resume Animation - KDCircularProgress Circular Bar

    相关文章

      网友评论

          本文标题:speed(CAMediaTiming)控制动画暂停和结束

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