首页 > 代码库 > CALayer 自定义属性绘制动画

CALayer 自定义属性绘制动画

创建CircleLayer继承CALayer,添加新属性angle。
@interfaceCircleLayer :CALayer
@property(nonatomic,assign)CGFloatangle;
@end
 
覆盖父类方法,添加新的属性动画键值,返回YES表示给定的属性发生变化时导致layer的内容重绘
+ (BOOL)needsDisplayForKey:(NSString*)key
{
   if([keyisEqualToString:@"angle"]) {
       returnYES;
    }
   return[superneedsDisplayForKey:key];
}
 
代码绘制部分
- (void)drawInContext:(CGContextRef)ctx
{
    CGFloat lineWidth = 3.0f;
    CGPoint centerPoint = CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
   
    CGContextBeginPath(ctx);
    CGContextAddArc(ctx, centerPoint.x, centerPoint.y, CGRectGetWidth(self.bounds)/2 -lineWidth/2, 0.0f, self.angle, 0);
    CGContextEndPage(ctx);
   
    CGContextSetStrokeColorWithColor(ctx, [UIColorredColor].CGColor);
    CGContextSetLineWidth(ctx, lineWidth);
    CGContextStrokePath(ctx);
}
 
创建CABasicAnimation动画
CircleLayer *layer = [CircleLayer layer];
layer.frame = CGRectMake(10, 100, 40, 40);
   
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"angle"];
animation.fromValue = http://www.mamicode.com/@(0.0f);
animation.toValue = http://www.mamicode.com/@(2*M_PI);
animation.repeatCount = MAXFLOAT;
animation.duration = 3.0f;
[layer addAnimation:animation forKey:@"angle_key"];
 
 

CALayer 自定义属性绘制动画