3

I'm trying to render a CATransformLayer that contains several CAShapeLayers to a png file. I know how to set up the basic rendering and that does work.

Though when I call renderInContext on the CATransformLayer, it flattens everything to 2D and completely ignores my transformation matrix (rotation and / or perspective).

What can I do to render my 3d CATransformLayer with all its CAShapeLayers to PNG / UIImage?

Max
  • 2,699
  • 2
  • 27
  • 50
  • 1
    According to the documentation, renderInContext: doesn't render 3D transformations. Question: are you targeting only iOS 7 and above? – TylerP May 08 '14 at 02:00
  • Hm, I see. Yes, I do. Is there a neat way to do it in iOS 7? – Max May 08 '14 at 10:04

1 Answers1

6

Since you're targeting only iOS7 and above, I would suggest you ditch renderInContext: and replace it with -[UIView drawViewHierarchyInRect:afterScreenUpdates:]. Your code will probably look something like this then:

UIGraphicsBeginImageContext(sizeOfYourImage);

[yourViewToRender drawViewHierarchyInRect:(CGRect){0, 0, sizeOfYourImage} afterScreenUpdates:YES];

UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
TylerP
  • 9,600
  • 4
  • 39
  • 43
  • Thank you! Made my day :) Though it would be cool to know of a way to render it without having to show it on the screen first. – Max May 08 '14 at 21:48
  • @Max Hmmm, you shouldn't have to show the view on the screen first before using this technique. In fact, I just now made a test project that renders a view hierarchy that is not added as a subview to any other view and it worked just fine. – TylerP May 08 '14 at 22:33
  • Ah okay great! That means I can also render images larger than the screen, that's nice. Do you know if this or another technique works to render to PDF with 3D Transforms applied (for vector graphics export, rendering a 3D hierarchy of CAShapeLayers to PDF)? – Max May 08 '14 at 22:41
  • Unfortunately I'm not too familiar with PDF rendering on iOS, but I can at least point you to the documentation that describes how to [generate PDF content](https://developer.apple.com/library/ios/documentation/2ddrawing/conceptual/drawingprintingios/GeneratingPDF/GeneratingPDF.html). Since you know how to get a UIImage from your view hierarchy, I imagine that if you can find a way to render that image to a PDF then you're good to go. Hope that helps! – TylerP May 08 '14 at 22:58
  • In short, it's finally possible to capture images that include active CATransform3D's using drawViewHierarchyInRect. Woohoo! – Bobjt Feb 12 '15 at 19:02