Search code examples
uiviewcore-graphicscalayer

Render layer of UIView which is not in the View Hierarchy


What i want to achieve is to take an image of an UIView which has not been added as a subview, present and do stuff with the image and afterwards add the view to the view hierarchy.

I've searched and tried now for a while and believe, that it is simply not possible.


Obviously the problem is, that the view hasn't been drawn (called drawRect: i guess) if it hasn't been added as a subview. Actually i thought renderInContext: would call drawRect/layer on its own.

It isn't even enough to add it as subview right before draw it to an imageContext because it won't be rendered immediately.

I take the screenshot with renderInContext: with the layer of the view, see my code here:

[self.view addSubView:view];
UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, -frame.origin.x, -frame.origin.y);

[view.layer renderInContext:context];

UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

So my question is, has anybody managed to render a not visible UIView and if how?


Solution

  • Well this is awkward.
    After a mail conversation with a very kind apple dev support, we reviewed my code and we noticed that i simply set the hidden property to YES. - Just don't do that.

    So it is straight forward to make a screenshot of a view which is not in the view hierarchy.
    It was total my fault why it didn't work.