在iPhone上屏蔽PNG图像的白色

时间:2009-11-11 10:25:59

标签: iphone graphics png alpha

我知道已有2篇相关帖子,但目前尚不清楚......

所以情况就是这样......:

我有一个UIImage,其中包含从网上网址请求的png文件。 是否可以掩盖白色以使其变得透明?

到目前为止我用CGImageCreateWithMaskingColors尝试的所有内容都会返回一张白色图片......

任何帮助人员都会很珍贵:)

2 个答案:

答案 0 :(得分:1)

好的,因为我找到了一个解决方案并且工作正常,我正在回答我的问题,我真的相信这对有很多需要的人有用。

首先,我认为通过类别扩展我的UIImages会很好:

<强>的UIImage + Utils.h

#import <UIKit/UIKit.h>

@interface UIImage (Utils)

- (UIImage*)imageByClearingWhitePixels;
@end

<强>的UIImage + Utils.m

#import "UIImage+Utils.h"

@implementation UIImage (Utils)

#pragma mark Private Methods
- (CGImageRef) CopyImageAndAddAlphaChannel:(CGImageRef) sourceImage {
    CGImageRef retVal = NULL;

    size_t width = CGImageGetWidth(sourceImage);
    size_t height = CGImageGetHeight(sourceImage);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);

    if (offscreenContext != NULL) {
        CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage);

        retVal = CGBitmapContextCreateImage(offscreenContext);
        CGContextRelease(offscreenContext);
    }

    CGColorSpaceRelease(colorSpace);

    return retVal;
}

- (UIImage *) getMaskedArtworkFromPicture:(UIImage *)image withMask:(UIImage *)mask{

    UIImage *maskedImage;
    CGImageRef imageRef = [self CopyImageAndAddAlphaChannel:image.CGImage];
    CGImageRef maskRef = mask.CGImage;
    CGImageRef maskToApply = CGImageMaskCreate(CGImageGetWidth(maskRef),CGImageGetHeight(maskRef),CGImageGetBitsPerComponent(maskRef),CGImageGetBitsPerPixel(maskRef),CGImageGetBytesPerRow(maskRef),CGImageGetDataProvider(maskRef), NULL, NO);
    CGImageRef masked = CGImageCreateWithMask(imageRef, maskToApply);
    maskedImage = [UIImage imageWithCGImage:masked];
    CGImageRelease(imageRef);
    CGImageRelease(maskToApply);
    CGImageRelease(masked);
    return maskedImage;

}

#pragma mark Public Methods
- (UIImage*)imageByClearingWhitePixels{

    //Copy image bitmaps
    float originalWidth = self.size.width;
    float originalHeight = self.size.height;
    CGSize newSize;

    newSize = CGSizeMake(originalWidth, originalHeight);

    UIGraphicsBeginImageContext( newSize );

    [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    //Clear white color by masking with self
    newImage = [self getMaskedArtworkFromPicture:newImage withMask:newImage];

    return newImage;
}

@end

最后,我能够像这样使用它:(当然我导入了UIImage+Utils.h之后)

UIImage *myImage = [...]; //A local png file or a file from a url
UIImage *myWhitelessImage = [myImage imageByClearingWhitePixels]; // Hooray!

答案 1 :(得分:0)

这是不可能的,至少没有简单的方法,当然也没有API调用。它基本上是一个通常用Photoshop完成的图像编辑问题。大多数具有透明背景的图像都是以这种方式创建的。