1.自定义layer方式一:
1>自定义一个NJCALayer类继承CALayer并重写方法:
- (void)drawInContext:(CGContextRef)ctx
{
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
CGContextFillPath(ctx);
}
2>在外部调用:
- (void)test
{
NJLayer *myLayer = [NJLayer layer];
myLayer.bounds = CGRectMake(0, 0, 100, 100);
myLayer.anchorPoint = CGPointZero;
myLayer.backgroundColor = [UIColor greenColor].CGColor;
[myLayer setNeedsDisplay];
[self.view.layer addSublayer:myLayer];
}
1.自定义layer方式二:创建系统的CALayer类,并实现代理方法,因为该方法是NSObject的方法,而所有的类都是NSObject的子类,所以不需要遵守协议:
1>
CALayer *myLayer = [CALayer layer];
myLayer.bounds = CGRectMake(0, 0, 100, 100);
myLayer.anchorPoint = CGPointZero;
myLayer.backgroundColor = [UIColor greenColor].CGColor;
myLayer.delegate = self;
[myLayer setNeedsDisplay];
[self.view.layer addSublayer:myLayer];
2>代理方法:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 100));
CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
CGContextFillPath(ctx);
}
3.在自定义view并实现drawRect的时候实际上系统会调用[self.layer drawInContext:ctx];进行绘图:
- (void)drawRect:(CGRect)rect
{
// 1.获取上下文 layer的上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
CGContextSetRGBFillColor(ctx, 1, 0, 0, 1);
CGContextFillPath(ctx);
}