Search code examples
objective-cioscocoa-touchcore-graphicsquartz-2d

CGContextRef not being created


-(CGImageRef)drawing{

CGContextRef    context;
GLubyte         *bitmapData;
size_t          width, height;

width=super.size.width;
height=super.size.height;

bitmapData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));

context = CGBitmapContextCreate(bitmapData, width, height, 8, width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);

if (context==NULL){
    NSLog(@"context not created?!   (o_*) ");
}

free(bitmapData);


CGContextSetRGBFillColor (context, 1, 0, 0, 1);
CGContextFillRect (context, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (context, 0, 0, 1, .5);
CGContextFillRect (context, CGRectMake (0, 0, 100, 200 ));




CGImageRef myImage = CGBitmapContextCreateImage (context);

CGContextRelease(context);

return myImage;

}

So i'm trying to render a drawing off screen in a context and then get it as a CGImageRef but for some reason the context is always NULL and the app crashes when i read the image output.

Can someone explain what's going on here and / or point me to an example where this works.


Solution

  • I don't know why the context is null - the width & height might be bad.

    But...

    1. You're freeing the bitmap before you use it!
    2. You can't release the color space you create.

    There's an example using CGBitmapContextCreate in the Quartz 2D Programming Guide.