Reputation: 10849
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 ...
<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.
Upvotes: 1
Views: 5237
Reputation: 10849
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.
Upvotes: 0
Reputation: 119242
It sounds like you are calling drawRect:
directly. So it is getting called once from your call, and once from the genuine drawing loop.
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.
Upvotes: 3