Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw CALayer into a CGContext

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?

like image 656
lucas Avatar asked May 26 '11 04:05

lucas


2 Answers

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.

like image 97
Luke Rogers Avatar answered Nov 16 '22 06:11

Luke Rogers


The coordinate system isn't messed up, per se. Quartz uses a different coordinate system than UIKit. In Quartz, the Y-axis originates at the bottom-left of the framing rectangle. The values become larger as you travel farther "up" the rectangle. For a visual representation, see the documentation at

http://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html

This differs from UIKit in that UIKit's coordinate system origin is the top-left with y-axis values becoming more positive as you travel "down".

As for why drawInContext: doesn't work, you should also reference the docs for the CALayer class where it says, "Default implementation does nothing."

http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html

like image 40
Jacob Avatar answered Nov 16 '22 07:11

Jacob