CALayer动画的暂停,恢复,以及结束时候的回调
源码如下:
// // 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
以下是需要注意的地方: