<Error>: CGContextSaveGState: invalid context 0x0 Error

Sagar... picture Sagar... · Dec 22, 2010 · Viewed 10.2k times · Source

I am getting some issue related with preparing the UIImage out of a UIView. I sometimes (but not always) see the error

<Error>: CGContextSaveGState: invalid context 0x0

I'm using the iPhone SDK 4.0. My code:

-(void)drawRect:(CGRect)rect
{
     // Customized to draw some text
}


-(UIImage*) PrepareBackImage:(CGRect) aRect // aRect = (0,0,1800,1200)
{
    UIImage* background;

    background      = [self GetImageFromView:self toRect:self.frame];
    UIGraphicsBeginImageContext(aRect.size);

    CGPoint backgroundPoint = CGPointMake(0,0);
    [background drawAtPoint:backgroundPoint];

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

    return backImage;
}

- (UIImage *) GetImageFromView:(UIView *)aView toRect:(CGRect)aRect
{
    CGSize pageSize = aRect.size;
    UIGraphicsBeginImageContext(pageSize);
    [aView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Answer

Jonathan Cichon picture Jonathan Cichon · Sep 11, 2012

The Error <Error>: CGContextSaveGState: invalid context 0x0 means either your CGContext is NULL or, the more reasonable explanation in your case, that the size of the Context is empty (CGSizeZero)