I have trying to do some complicated drawing by swift. What I am trying to do is that I first draw my CGPath on a CALayer, and that add the CALayer on to the bottom view. (Since I need to use different blend mode in the CALayer and between different CALayers) However, I am found there is a significant difference in CALayer's draw function and that of UIView
//UIView's draw function
func draw(_ rect: CGRect)
//CALayer's draw function
func draw(in ctx: CGContext)
I have noticed that I have to give CALayer a CGContext, does it mean that CALayer can not draw itself? What's the difference between the drawing of UIView and that of CALayer?
You do not give the layer a context. It has a context already; when it calls draw(in:)
it simply hands you a reference to that context so you can draw in it explicitly. This is actually nicer than what a view does, because with a view, you have to get a reference to the context by calling UIGraphicsGetCurrentContext.
Still, there is usually no need to use the layer's draw method if the layer belongs to a view — because you've got the view draw method instead. A layer draw method is usually needed only when the layer is not a view's underlaying layer.
Please note that you never call either of those methods! They are called for you. What you do is implement them so that when they are called, you are there, ready to say what drawing should go into the view / layer.