上篇列举了一些非常相像的方法,这里继续讨论另外一个非常相似的方法:
UIView:
- (void)drawRect:(CGRect)rect;
CALayer:
- (void)display;
drawRect方法大概大家都比较熟悉,而CALayer的display可能会比较陌生,我们来看看文档怎么描述:
/* Reload the content of this layer. Calls the -drawInContext: method
* then updates the `contents' property of the layer. Typically this is
* not called directly. */
“重载层的内容,调用drawInContext方法,并且更新层的contents属性,这个方法通常来说不直接调用”
再来看看详细的部分:
总的来说就是在适当时机重载层的内容,如果层具备代理对象,会用代理对象调用代理的:displayLayer:方法来更新层的内容,这个方法是可选的,如果没有实现的话,层灰创建一个backing store并且调用自己的drawInContext方法来将这个backing Store来填充内容,或者替代旧的backing Store。(关于backing store可以自己去了解一下渲染和图形绘制的知识)
我们分别重写它们:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
NSLog(@"UIView drawRect");
}
- (void)display
{
[super display];
NSLog(@"CALayer display");
}
并且打上断点,但是因为drawRect需要UIView被添加到view上(自行百度drawRect调用条件),我们补充代码:
CustomerView* aView = [[CustomerView alloc] init];
[aView setFrame:CGRectMake(0, 0, 50, 50)];
[aView setBackgroundColor:[UIColor blackColor]];
[self.view addSubview:aView];
可以看到:
清楚看到,先调用CALayer的display方法,然后就去调用UIView的drawRect方法了!而drawRect是不是内容调用了drawLayer:inContext来实现?很有可能!!
drawLayer:inContext 和上面提到的方法,以后都会去做个专题学习!
另外,其实还有两个非常值得对比的方法:
CALayer的:
- (void)drawInContext:(CGContextRef)ctx
UIView的:
- (void)drawRect:(CGRect)rect
但是通过测试,CALayer的drawInContext需要调用另外一个方法才会执行,所以自定义的时候需要注意:
- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)r;
而UIView的可以自动执行。
而这两个方法究竟有什么关系呢?通过这个可以很好地看出:
- (void)drawRect:(CGRect)rect
{
//1.获取上下文
CGContextRef ctx=UIGraphicsGetCurrentContext();
//2.绘制图形
CGContextAddEllipseInRect(ctx, CGRectMake(50, 50, 100, 100));
//设置属性(颜色)
// [[UIColor yellowColor]set];
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
//3.渲染
CGContextFillPath(ctx);
//在执行渲染操作的时候,本质上它的内部相当于调用了下面的方法
[self.layer drawInContext:ctx];
}