简体   繁体   中英

Creating a mask from a graphics context

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM