关于Layer的一些知识

1.当一个view被addsubview到其他view上时

1.先隐式地把此view的layer的CALayerDelegate设置成此view
2.调用此view的self.layer的drawInContext方法
3.由于drawLayer方法的注释 If defined, called by the default implementation of -drawInContext:
说明了drawInContext里if([self.delegate responseToSelector:@selector(drawLayer:inContext:)])时就执行drawLayer:inContext:方法,这里我们因为实现了drawLayer:inContext:所以会执行
4.[super drawLayer:layer inContext:ctx]会让系统自动调用此view的drawRect:方法
至此self.layer画出来了
5.在self.layer上再加一个子layer来绘图,当调用[layer setNeedsDisplay];时会自动调用此layer的drawInContext方法。drawInContext方法不能手动调用,只能通过这个方法让系统自动调用
6.如果drawRect不重写,就不会调用其layer的drawInContext方法,也就不会调用drawLayer:inContext方法

2.在UIView的drawRect:rect方法中

1.直接用UIKit提供的绘图如UIBezierPath去stroke描边,fill填充。
2.也可以用CoreGraphics在ctx上绘图
需要先UIGraphicsGetCurrentContext()得到上下文CGContextDrawPath(ctx,kCGPathFillStroke);//既有填充又有边框

3.在CALayer的delegate方法drawLayer: inContext:中。

1.直接用UIKit提供的绘图
需要UIGraphicsPushContext(ctx);把当ctx转为当前上下文,可用UIBezierPath的stroke,fill去画,画完图再UIGraphicsPopContext();
2.也可以用CoreGraphics在ctx上绘图
直接用传过来的ctx即可。如:CGContextFillPath(ctx);

原文地址:https://www.cnblogs.com/lizhen24/p/6068405.html