Changing the background colour of a CGContext

DaveDee picture DaveDee · Jan 24, 2012 · Viewed 9k times · Source

i'm really new to dealing with CGContexts and i'm just trying to get my head around things by following a simple touch paint & sketch tutorial (http://blog.effectiveui.com/?p=8105)

I have hit a brick wall when it's come to changing the background colour of my CGContext though.

I'm initiating the conext like this:

 - (BOOL) initContext:(CGSize)size {
     int bitmapBytesPerRow;
     bitmapBytesPerRow = (size.width * 4);
     cacheContext = CGBitmapContextCreate (nil, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast);
     CGContextSetRGBFillColor(cacheContext, 1, 1, 1, 1);
     return YES;
 }

and changing stroke colours and widths like this:

UIColor *color = [UIColor whiteColor];
CGContextSetStrokeColorWithColor(cacheContext, [color CGColor]);
CGContextSetLineCap(cacheContext, kCGLineCapRound); 
CGContextSetLineWidth(cacheContext, 4);

but when i try to change the background colour from black (either in the init or in the drawing/stroke set-up parts) using CGContextSetRGBFillColor(cacheContext, 1, 1, 1, 1); there is no effect.

Is anyone able to point me in the right direction of either a better/correct place to put that call, or the correct call to use? Many thanks for your time!

Answer

Lily Ballard picture Lily Ballard · Jan 24, 2012

You can't just set the color and expect the context to fill with the new color. You need to actually draw that color into the context. In the init method, after setting the fill color, try using something like

CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});

On a related note, context don't have a black color by default. They have a transparent color. Now, if your context doesn't have an alpha channel, then this will end up being black, but if your context does have an alpha channel and you're seeing black, it's because you're rendering the output on top of something black (or, alternately, you're putting the transparent image into a layer that has the opaque flag set to true and CoreAnimation ends up drawing it on top of black).