Non-null invalid context error when creating a UIImage from a UIView

cgcontext, iphone, uiimage, uiview

Solution

I had a similar issue but was able to solve it by pushing and popping the image context prior to my layer rendering its contents.

Try something like this:

UIImage *snapshotImage = nil;
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, view.layer.contentsScale);
{
    CGContextRef imageContext = UIGraphicsGetCurrentContext();

    if (imageContext != NULL) {
        UIGraphicsPushContext(imageContext);
        {
            [view.layer renderInContext:imageContext];
        }
        UIGraphicsPopContext();
    }

    snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();

For what it's worth, there are alternative (and more efficient) ways to obtain a snapshot but it's still under NDA.

Problem

I'm using the following to generate a UIImage from a UIView ``` UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, [[UIScreen mainScreen] scale]); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage* img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); ``` which usually works but about half the time, I get this error when renderInContext is called: ``` <Error>: CGContextDrawImage: invalid context 0x84d0b20 ``` Does anyone have any idea why this happens or how to even detect when it happens? I think I would feel better if the address for the context was 0x0 because it would at least be something I could test for and deal with but this so far this has me stumped. Edit: Whoops. Meant to use view.frame.size and not view.bounds.size.

Original source