如何更改颜色'白色'从UIImage到透明

时间:2012-02-26 23:26:42

标签: iphone image uiimage transparent masking

我有一个UIImage作为截图生成。我正在使用以下代码添加此对象:

self.view.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.0];
    drawImage.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.0];

    UIGraphicsBeginImageContext(self.view.bounds.size);
    [drawImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef rawImageRef=viewImage.CGImage;
    const float colorMasking[6] = {255,255,255,255,0,0}; 
    CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
    UIImage *newImage = [UIImage imageWithCGImage:rawImageRef];

然而,我的图像只会变成白色,我希望使用CGImageCreateMaskingColors让图像在白色的地方透明。

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:6)

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 1.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef rawImageRef = viewImage.CGImage;
const float colorMasking[6] = {255, 255, 255, 255, 255, 255};
UIGraphicsBeginImageContext(viewImage.size);
CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, viewImage.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);

CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, viewImage.size.width, viewImage.size.height), maskedImageRef);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
CGImageRelease(maskedImageRef);
UIGraphicsEndImageContext();