What's the difference between CALayer -drawInContext: and -renderInContext:?

dontWatchMyProfile picture dontWatchMyProfile · Mar 30, 2010 · Viewed 8.9k times · Source

What's the difference between CALayer -drawInContext: and -renderInContext: ?

Answer

Brad Larson picture Brad Larson · Mar 30, 2010

When providing custom Quartz-drawn content to display within a CALayer, you can override -drawInContext: and do your custom drawing there. This is similar to -drawRect: for a UIView or NSView. Alternatively, you can set another class to be the delegate of the CALayer and implement -drawLayer:inContext: to provide custom content to a standard CALayer.

You don't override -renderInContext:, but instead you can call this on a layer to render it and all of its sublayers into a particular Core Graphics context. Note that this won't render certain types of layers (like those with OpenGL content). It also doesn't behave the way you'd expect when rendering into a PDF context, where the layers will come out as bitmapped rectangles instead of pure vector elements. To work around this, you might want to check out the Core Plot framework's CPTLayer implementation, where we bypass the normal rendering process in order to preserve the vectors in a PDF generated from our CALayer subclass.