开发者

Issue Creating and Masking a Solid Color CGImage

开发者 https://www.devze.com 2023-03-29 05:20 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号