码迷,mamicode.com
首页 > 其他好文 > 详细

CALayer动画的暂停,恢复,以及结束时候的回调

时间:2014-11-07 14:22:09      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

CALayer动画的暂停,恢复,以及结束时候的回调

bubuko.com,布布扣

源码如下:

//
//  ViewController.m
//  AnimationLineView
//
//  Created by YouXianMing on 14/11/7.
//  Copyright (c) 2014年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "YXGCD.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // layer
    CALayer *layer        = [CALayer layer];
    layer.frame           = CGRectMake(100, 100, 3, 3);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.delegate        = self;
    [self.view.layer addSublayer:layer];
    
    // 动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    animation.fromValue         = [NSValue valueWithCGRect:layer.frame];
    animation.toValue           = [NSValue valueWithCGRect:CGRectMake(100, 100, 100, 3)];
    animation.duration          = 3.f;
    animation.delegate          = self;                   // 设置代理
    [layer addAnimation:animation forKey:@"YouXianMing"]; // 添加动画
    
    // 暂停动画
    [GCDQueue executeInMainQueue:^{
        [self pauseLayer:layer];
    } afterDelaySecs:1.5f];
    
    // 恢复动画
    [GCDQueue executeInMainQueue:^{
        [self resumeLayer:layer];
    } afterDelaySecs:3.f];
    
    // 移除动画(根据key值)
    [GCDQueue executeInMainQueue:^{
        [layer removeAnimationForKey:@"YouXianMing"];
    } afterDelaySecs:3.5f];
}

/**
 *  动画确实停止了
 *
 *  @param anim CAAnimation对象
 *  @param flag 是否是正常的移除
 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    NSLog(@"动画:%@ 是否动画中途被移除了:%d", anim, flag);
}

/**
 *  暂停
 *
 *  @param layer 被停止的layer
 */
-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed               = 0.0;
    layer.timeOffset          = pausedTime;
}

/**
 *  恢复
 *
 *  @param layer 被恢复的layer
 */
-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime     = [layer timeOffset];
    layer.speed                   = 1.0;
    layer.timeOffset              = 0.0;
    layer.beginTime               = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime               = timeSincePause;
}

@end

以下是需要注意的地方:

bubuko.com,布布扣

bubuko.com,布布扣

 

CALayer动画的暂停,恢复,以及结束时候的回调

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/YouXianMing/p/4081143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!