Issue Creating and Masking a Solid Color CGImage
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 = CGColorSpaceCreateDeviceRGB();
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.
链接地址: http://www.djcxy.com/p/46524.html上一篇: 如何在Xcode中通过帧获取图片帧
下一篇: 问题创建和遮蔽纯色CGImage
