iphone - 如何将颜色 'white' 从 UIImage 更改为透明

标签 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 让图像在白色的地方变得透明。

希望有人能帮助我。

最佳答案

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();

关于iphone - 如何将颜色 'white' 从 UIImage 更改为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458303/

相关文章:

iphone - 另一个 ScrollView 内的 ScrollView 内的 TableView

iphone - UILabel sizeToFit - 调整下方对象的位置

javascript - 将原始图像绘制到 Canvas 中

css - 相对定位的 div 内的绝对定位淡入淡出图像不起作用

iphone - 在 UIImage 上创建褪色的角/边(不是动画)

ios - 在 Swift 中合并两个滚动和缩放的图像

ios - 如何在 iOS 中将 uilabel 图标与文本对齐

iphone - 如何借助CCDirector将场景替换为某些 Action ?

ios - UIScrolView 中的 UIImageView。如何在 iphone 6 和 6 plus 中按比例缩放 UIImageView

c++ - 在 boost::gil 中读取图像和访问字节