In an iPhone
app I have a set of black and white images. I need a function which changes the white areas of the image to transparent and the black to an arbitrary color.
I'm trying to create a solid color (black or white) CGImageRef
and then masking it with my original image. It's almost working, but the areas which should be transparent are about 1% transparent.
Here is the function I have. It accepts a boolean
to determine whether the solid color
should be black or white.
- (UIImage*) imageWithMask:(UIImage *) maskImage andIsWhite:(BOOL) isWhite { CGImageRef maskImageRef = [maskImage CGImage]; CGColorSpaceRef colorSpace = CGCol开发者_如何学编程orSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, maskImage.size.width, maskImage.size.width, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); if (isWhite) { CGContextSetRGBFillColor(context, (CGFloat)1.0, (CGFloat)1.0, (CGFloat)1.0, (CGFloat)1.0 ); } else { CGContextSetRGBFillColor(context, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)1.0 ); } CGContextAddRect(context, CGRectMake(0, 0, maskImage.size.width, maskImage.size.height)); CGContextFillRect(context, CGRectMake(0, 0, maskImage.size.width, maskImage.size.height)); CGImageRef solidImage = CGBitmapContextCreateImage(context); CGColorSpaceRelease(colorSpace); CGContextRelease(context); CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskImageRef), CGImageGetHeight(maskImageRef), CGImageGetBitsPerComponent(maskImageRef), CGImageGetBitsPerPixel(maskImageRef), CGImageGetBytesPerRow(maskImageRef), CGImageGetDataProvider(maskImageRef), NULL, false); CGImageRef masked = CGImageCreateWithMask(solidImage, mask); UIImage *maskedUIImage = [UIImage imageWithCGImage:masked]; CGImageRelease(masked); return maskedUIImage; }
Any suggestions are appreciated.
精彩评论