iOS Core Animation学习总结(2)--实现自定义图层

时间:2022-02-19 11:39:43

一. 创建图层继承于CALayer,并在子类实现drawInContext方法

@interface CTLayer : CALayer

@end

@implementation CTLayer
-(void)drawInContext:(CGContextRef)ctx{
   //画一个圆
CGContextSetRGBFillColor(ctx, , , , );
CGContextAddEllipseInRect(ctx, CGRectMake(, , , ));
CGContextFillPath(ctx);
}
@end

在viewcontroller加载视图时,

    CTLayer *layer = [CTLayer layer];
layer.bounds = CGRectMake(, , , );
layer.anchorPoint = CGPointMake(,);
[layer setNeedsDisplay];//显示图层
[self.view.layer addSublayer:layer];

二. 使用代理方式创建

    CTLayer *layer = [CTLayer layer];
layer.bounds = CGRectMake(, , , );
layer.anchorPoint = CGPointMake(,);
layer.delegate = self; //指定代理,该代理可为任意类型
[layer setNeedsDisplay];//显示layer
[self.view.layer addSublayer:layer];

实现代理方法

#pragma mark 代理方法
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGContextSetRGBFillColor(ctx, , , , );
CGContextAddEllipseInRect(ctx, CGRectMake(, , , ));
CGContextFillPath(ctx);
}