Search code examples
ioscore-graphicscalayer

How do I use CALayer renderInContext and keep the perspective transform?


How do I use CALayer renderInContext and have the perspective transform (m34) of the layer preserved? It seems like this method assumes an Identity transform. I have tried things like transforming the context, and this is fine for translation, rotation and scaling, but there does not seem to be a way to keep the perspective of the 3D transform.

Maybe a better way to put this question: How do I apply a perspective while drawing to a CGContextRef?


Solution

  • You might want to have a look at the method drawViewHierarchyInRect:afterScreenUpdates: which is offered since iOS 7.0. Applying the method to the view containing the CALayers will keep their 3D transformations.

    Sample code:

    BOOL opaqueBackground = YES;
    UIGraphicsBeginImageContextWithOptions(theViewContainingYourCALayers.bounds.size, !opaqueBackground, 0);
    [theViewContainingYourCALayers drawViewHierarchyInRect:theViewContainingYourCALayers.bounds afterScreenUpdates:YES];
    [UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    As matt pointed out, relying solely on renderInContext: is not possible since it disregards any transformation other than affine ones.

    Late answer but I hope it still helps.