tags:

views:

73

answers:

2

Please note that this question is about CGLayer (which you typically use to draw offscreen), it is not about CALayer.

In iOS, what's the correct code to save a CGLayer as a PNG file? Thanks!

Again, that's CGLayer, not CALayer.

Note that you CAN NOT use UIGraphicsGetImageFromCurrentImageContext.

(From the documentation, "You can call UIGraphicsGetImageFromCurrentImageContext only when a bitmap-based graphics context is the current graphics context.")

Note that you CAN NOT use renderInContext:. renderInContext: is strictly for CALayers. CGLayers are totally different.

So, how can you actually convert a CGLayer to a PNG image? Or indeed, how to render a CGLayer in to a bitmap in some way (of course you can then easily save as an image).

------------ LATER
------------ LATER
------------ LATER .. Ken has completely answered this difficult question. I will paste in a long example code that may help people, in a separate answer below. Thanks again Ken! Amazing!!!!

+1  A: 

For iPhone OS, it should be possible to draw a CGLayer on a CGContext and then convert into a UIImage, which can then be encoded into PNG and saved.

CGSize size = CGLayerGetSize(layer);
UIGraphicsBeginImageContext(size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextDrawLayerAtPoint(ctx, CGPointZero, layer);
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
NSData* pngData = UIImagePNGRepresentation(image);
[pngData writeToFile:... atomically:YES];
UIGraphicsEndImageContext();

(not tested)

KennyTM