如何监听Core animation progress callback?

思想步骤:
1.首先创建继承CALayer子类TAProgressLayer,包含progress属性

2.将TAProgressLayer添加到图层🌲上,并且添加动画,设置0<=progress<=1

3.在drawInContext调用代理函数

具体实现:
'''javascript

@protocol TAProgressLayerProtocol <NSObject>

- (void)progressUpdatedTo:(CGFloat)progress;

@end

@interface TAProgressLayer : CALayer

@property CGFloat progress;
@property (weak) id<TAProgressLayerProtocol>  delegate;
@end

@implementation TAProgressLayer
@implementation TAProgressLayer

// We must copy across our custom properties since Core Animation makes a copy
// of the layer that it's animating.

- (id)initWithLayer:(id)layer
{
self = [super initWithLayer:layer];
if (self) {
    TAProgressLayer *otherLayer = (TAProgressLayer *)layer;
    self.progress = otherLayer.progress;
    self.delegate = otherLayer.delegate;
}
return self;
}

// Override needsDisplayForKey so that we can define progress as being animatable.

+ (BOOL)needsDisplayForKey:(NSString*)key {
if ([key isEqualToString:@"progress"]) {
    return YES;
} else {
    return [super needsDisplayForKey:key];
}
 }

// Call our callback

- (void)drawInContext:(CGContextRef)ctx
{
    if (self.delegate)
    {
        [self.delegate progressUpdatedTo:self.progress];
    }
}

@end

// We can then add the layer to our main layer:
TAProgressLayer *progressLayer = [TAProgressLayer layer];
progressLayer.frame = CGRectMake(0, -1, 1, 1);
progressLayer.delegate = self;
[_sceneView.layer addSublayer:progressLayer];
And animate it along with the other animations:

CABasicAnimation *anim = [CABasicAnimation   animationWithKeyPath:@"progress"];
 anim.duration = 4.0;
anim.beginTime = 0;
anim.fromValue = @0;
anim.toValue = @1;
anim.fillMode = kCAFillModeForwards;
anim.removedOnCompletion = NO;
[progressLayer addAnimation:anim forKey:@"progress"];

'''
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容