我定义了一个自定义层,并声明了一个自定义属性,但是在 -(void)drawInContext:(CGContextRef)ctx 方法中的动画时它不起作用
这是一些代码:
@interface ZBBProgressLayer : CAShapeLayer
@property (nonatomic, assign) CGFloat progress;
@property(nullable) CGColorRef progressColor;
@end
@implementation ZBBProgressLayer
+ (BOOL)needsDisplayForKey:(NSString *)key{
if ([key isEqualToString:@"progress"]/*progress 属性变化时,重绘*/) {
return YES;
}
return [super needsDisplayForKey:key];
}
-(void)dealloc{
[self removeAllAnimations];
}
@end
// ZBBRectProgressLayer
@interface ZBBRectProgressLayer : ZBBProgressLayer
@end
@implementation ZBBRectProgressLayer
-(void)drawInContext:(CGContextRef)ctx{
CGSize boundsSize = self.bounds.size;
CGFloat width = boundsSize.width * self.progress;
UIBezierPath *cutoutPath =[UIBezierPath bezierPathWithRect:CGRectMake(0,
0,
width,
boundsSize.height)];
CGContextSetFillColorWithColor(ctx,self.progressColor);
CGContextAddPath(ctx, cutoutPath.CGPath);
CGContextFillPath(ctx);
// NSLog(@"%@ = %@\n",[self class],self);
}
@end
我使用这样的图层:
-(void)setProgress:(CGFloat)progress animated:(BOOL)animated{
_progress = MIN(progress, 1);
if (animated) {
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"progress"];
animation.duration = kAnimationDurationTime;
animation.fromValue = @(_maskLayer.progress);
animation.toValue = @(_progress);
[_maskLayer addAnimation:animation forKey:@"progress"];
_maskLayer.progress = _progress;
}else{
_maskLayer.progress = _progress;
[_maskLayer performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES];
}
}
但是动画 == true,custom layer.progressColor 是 nil,animated == false,custom layer.progressColor 是正确的。