Question

I am creating my own context using CGBitmapContextCreate call. The context is created successfully. I can draw an UIImage in this context using the call CGContextDrawImage successfully. But, when I try to use the call drawPatternInRect: of UIImage, it gives the error 'Context is nil'.

I am sure that context is not nil and it is created properly because, CGContextDrawImage is working fine in the same context. The drawPatternInRect: call works fine only when the context is of UIView OR if I create the context in drawRect method of UIView. But, I cannot use UIView's context since I need to generate UIImage out of this context.

Does anyone knows what is the problem here OR any other alternate simple method for drawPatternInRect?

Was it helpful?

Solution

There is an additional concept relating to graphics contexts in Cocoa. In Core Graphics there is the CGContextRef which has to be passed to every CG drawing call as an explicit parameter. In many other places in iOS there is the concept of the current context which is a global current context (global for each thread) as an implied parameter to many drawing calls. Many APIs including UIImage draw in the current context. See the header UIGraphics.h.

Normally the current context is setup for you by the view system before drawRect: is called which is why drawing seems to work in these cases. In the case where you have created the context yourself you need to explicitly setup the current context. This code should work for you:

UIGraphicsPushContext( yourCGContext );

// Do your drawing here

UIGraphicsPopContext();

On the Mac things are similar using NSGraphics context, See Apple's documentation for NSGraphicsContext.

NSGraphicsContext* nsGraphicsContext = [ NSGraphicsContext 
        graphicsContextWithGraphicsPort: yourCGContext flipped: NO ];
[ NSGraphicsContext saveGraphicsState ];
[ NSGraphicsContext setCurrentContext: nsGraphicsContext ];

// Do your drawing here

[ NSGraphicsContext restoreGraphicsState ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top