draw CALayer into a CGContext

lucas picture lucas · May 26, 2011 · Viewed 7.3k times · Source

I have the following code:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);

CALayer *sublayer = [CALayer layer];
sublayer.backgroundColor = [UIColor orangeColor].CGColor;
sublayer.cornerRadius = 20.0;
sublayer.frame = CGRectMake(20, 0, 300, 20);

[sublayer setNeedsDisplay];
[sublayer drawInContext:context];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return newImage;

But when i view the return newImage, there is just an empty image. When i change drawInContext to renderInContext, then i got the above sublayer, but it seems like the coordinate system is mess up.

Any idea why drawInContext on the above did not work?

Answer

Luke Rogers picture Luke Rogers · Jun 26, 2015

Try using renderInContext in place of drawInContext.

My understanding is that drawInContext is there to be overridden, whereas renderInContext is used to render the contents of a layer to the context.

From the documentation:

- drawInContext:

The default implementation of this method does not doing any drawing itself. If the layer’s delegate implements the drawLayer:inContext: method, that method is called to do the actual drawing.

Subclasses can override this method and use it to draw the layer’s content. When drawing, all coordinates should be specified in points in the logical coordinate space.


- renderInContext:

This method renders directly from the layer tree, ignoring any animations added to the render tree. Renders in the coordinate space of the layer.