invalid context error when drawing a UIImage

I am trying to draw a UIImage to the context of my UIView. I’ve used this code with the context stuff commented in and out …

- (void)drawRect:(CGRect)rect
{
    //UIGraphicsBeginImageContextWithOptions(rect.size,YES,[[UIScreen mainScreen] scale]);
    //UIGraphicsBeginImageContext(rect.size);

    UIImage *newImage = [UIImage imageNamed:@"character_1_0001.png"];
    //[newImage drawAtPoint:CGPointMake(200, 200)];
    [newImage drawInRect:rect];

    //UIGraphicsEndImageContext();
}

As I understand it I shouldn’t need to set the image context to do this and indeed without it I do see the image drawn in the view but I also get this error in the log …

  • Continuous integration with Xcode Bots
  • Getting server data for the Apple Watch
  • Large database - Best way to display data on device?
  • iOS forces rounded corners and glare on inputs
  • UITableViewCell + Dynamic Height + Auto Layout
  • Xamarin iOS localization using .NET
  • <Error>: CGContextSaveGState: invalid context 0x0
    

    If I uncomment the UIGraphicsBeginImageContext lines I don’t get anything drawn and no error.

    Do I need to use the default graphics context and declare this somehow?

    I need to draw the image because I want to add to it on the context and can’t just generate a load of UIImageView objects.

    2 Solutions Collect From Internet About “invalid context error when drawing a UIImage”

    It sounds like you are calling drawRect: directly. So it is getting called once from your call, and once from the genuine drawing loop.

    • With the context creation present, you do all the drawing in a new context then discard it, so you never see anything
    • With the context creation missing, you get the error from the manually called drawRect:, and the actual drawing takes place in the genuine drawRect: so you see your image.

    Don’t call drawRect: directly. Call setNeedsDisplay and drawRect: will be called for you at the appropriate point.

    I discovered what was happening. The ViewController host of my custom UIView was instantiating a CALayer object. This was some old code that was previously being used as the drawing layer for a bitmap from an AVCaptureSession that I am using to generate my image.

    I’m now not using the CALayer and am instead just drawing a slice of each frame of video onto the default graphics context in my view.

    For some reason the instantiation of this CALayer was causing the conflict in the context.

    Now it is not being used I only need to use the following code to draw the image …

    - (void)drawRect:(CGRect)rect
    {
        UIImage *newImage = [UIImage imageNamed:@"character_1_0001.png"];
        [newImage drawInRect:rect];
    }
    

    Now I just do the same thing with an image that I pass in as a CGImageRef and adjust the rect … hopefully.