David Kanarek
David Kanarek

Reputation: 12613

Creating a reusable image from a Core Graphics context gives me nothing

I'm trying to speed up my drawing code. Instead of creating a graphics context, drawing the current image into it, and drawing over it, I'm trying to create a context using some pixel data, and just modify that directly. The problem is, I'm pretty new to core graphics and I can't create the initial image. I want just a solid red image, but I get nothing. Here's what I'm using for the initial image. I assume the problem will be the same with the rest of the code.

pixels = malloc(320*460*4);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixels, 320, 460, 8, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextAddRect(context, CGRectMake(0, 0, 320, 460));
CGContextFillPath(context);
trace = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()];
CGContextRelease(context);

Edit: UIGraphicsGetImageFromCurrentImageContext() turned out to be the problem. A working solution follows, but note that this is no faster than the much simpler UIGraphicsBeginImageContext()

pixels = malloc(320*460*4);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixels, 320, 460, 8, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextAddRect(context, CGRectMake(0, 0, 320, 460));
CGContextFillPath(context);
CGDataProviderRef dp = CGDataProviderCreateWithData(NULL, pixels, 320*460*4, NULL);
CGImageRef img = CGImageCreate(320, 460, 8, 32, 4*320, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, dp, NULL, NO, kCGRenderingIntentDefault);
trace = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:img]];
CGImageRelease(img);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);

Upvotes: 1

Views: 1604

Answers (1)

Ben Zotto
Ben Zotto

Reputation: 71018

For starters, it seems like the context you're drawing to is unconnected to the UIGraphics "current image context". Have you called UIGraphicsBeginImageContext(CGSize size) somewhere?

Not sure that will get you what you need, but it certainly means you're less likely to get nil back as the current image context.

Upvotes: 1

Related Questions