views:

212

answers:

1

I want to be able to create a greyscale image with no alpha from a png in the app bundle.

This works, and I get an image created:

// Create graphics context the size of the overlapping rectangle
UIGraphicsBeginImageContext(rectangleOfOverlap.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();

// More stuff

CGContextDrawImage(ctx, drawRect2, [UIImage imageNamed:@"Image 01.png"].CGImage);

// Create the new UIImage from the context
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

However the resulting image is 32 bits per pixel and has an alpha channel, so when I use CGCreateImageWithMask it doesn't work. I've tried creating a bitmap context thus:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef ctx =CGBitmapContextCreate(nil, rectangleOfOverlap.size.width, rectangleOfOverlap.size.height, 8, rectangleOfOverlap.size.width , colorSpace, kCGImageAlphaNone);

UIGraphicsGetImageFromCurrentImageContext returns zero and the resulting image is not created. Am I doing something dumb here?

Any help would be greatly appreciated.

Regards

Dave

A: 

OK, think I have an answer (or several of them)...

If the context create fails then the console window gives a reasonable error message and tells you why it failed. In this case the context is created, so no error.

Secondly the list of supported parameters for the CGBtimapContext is here: http://developer.apple.com/mac/library/qa/qa2001/qa1037.html

Thirdly UIGraphicsGetImageFromCurrentImageContext() only works with a generic context created using UIGraphicsBeginGraphicsContext() I needed to use:

UIImage *newImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(ctx)];

and forthly, I cannot get at the underlying pixel data with CGBitmapContextGetData(ctx) if I create the context using NULL as the first parameter, even though the docs imply that from 10.3 onwards memory is handled for you. To get around this I created a method called:

- (CGContextRef) newGreyScaleBitmapContextOfSize:(CGSize) size;

The method creates the context by malloc'ing the memory and returns a context ref. I am not sure if that is comprehensive, but as I've spent days on this I thought I'd let you know what I have discovered so far.

Hope this helps,

Dave

Magic Bullet Dave
You should only use `CGBitmapContextCreateImage` if you explicitly want a copy. The standard usage is to create an image and bitmap that refer to the same pixels, not copy the pixels each time.
drawnonward
Not sure I fully understand what you mean. I understand the sentiment but not how you mean in practice. Any chance you could post a few lines of code to cement my understanding. Sorry I know this is a newbie request...Dave
Magic Bullet Dave