一、自定义层的方法1
方法:
1> 创建一个CALayer的子类
@interface MyLayer : CALayer
2>然后覆盖drawInContext方法,使用Quartz2D API 进行绘制
- (void)drawInContext:(CGContextRef)ctx{
// 设置颜色
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
// 设置起点
CGContextMoveToPoint(ctx, 50, 50);
// 连线
CGContextAddLineToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 0, 100);
// 合并路径
CGContextClosePath(ctx);
// 绘制路径
CGContextFillPath(ctx);
}
3> 创建layer
MyLayer* layer = [MyLayer layer];
layer.bounds = CGRectMake(50, 50, 150, 150);
layer.position = CGPointMake(100, 100);
// 绘制图层 ,需要调用setNeedsDisplay这个方法,才会触发drawInContext:方法的调用,然后进行绘图
[layer setNeedsDisplay];
[self.view.layer addSublayer:layer];
二、自定义层的方法2
方法描述:设置CALayer的delegate,然后让delegate实现drawLayer:inContext:方法,当CALayer需要绘图时,会调用delegate的drawLayer:inContext:方法进行绘图。
* 这里要注意的是:不能再将某个UIView设置为CALayer的delegate,因为UIView对象已经是它内部根层的delegate,再次设置为其他层的delegate就会出问题。UIView和它内部CALayer的默认关系图:
1.创建新的层,设置delegate,然后添加到控制器的view的layer中
CALayer* layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 150, 150);
layer.position = CGPointMake(100, 100);
layer.delegate = self;
[layer setNeedsDisplay];
[self.view.layer addSublayer:layer];
2.实现代理方法
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
CGContextSetLineWidth(ctx, 5);
// CGContextFillRect(ctx, CGRectMake(10, 10, 50, 50));
CGContextStrokeRect(ctx, CGRectMake(10, 10, 50, 50));
}
三、总结
无论采取哪种方法来自定义层,都必须调用CALayer的setNeedsDisplay方法才能正常绘图。
* 当UIView需要显示时,它内部的层会准备好一个CGContextRef(图形上下文),然后调用delegate(这里就是UIView)的drawLayer:inContext:方法,并且传入已经准备好的CGContextRef对象。而UIView在drawLayer:inContext:方法中又会调用自己的drawRect:方法
* 平时在drawRect:中通过UIGraphicsGetCurrentContext()获取的就是由层传入的CGContextRef对象,在drawRect:中完成的所有绘图都会填入层的CGContextRef中,然后被拷贝至屏幕