【问题标题】:How to mask a UIImage so that white becomes transparent on iphone?如何掩盖 UIImage 使白色在 iphone 上变得透明?
【发布时间】:2009-07-10 07:50:08
【问题描述】:

我有一个白色背景的 UIImage(由用户绘图生成)。我想让这张图片的白色部分透明。我还想将其保存为 PNG 文件。

我在论坛上四处张望,但无法弄清楚如何正确屏蔽图像。以前有人试过吗?

谢谢。

【问题讨论】:

标签: iphone uiimage core-graphics quartz-graphics


【解决方案1】:

试试这样的...

CGImageRef myMaskedImage = [myImage CGImage];
const float whiteMask[6] = { 255,255,255, 255,255,255 };
CGImageRef myColorMaskedImage = CGImageCreateWithMaskingColors(image, whiteMask);

CGDataProviderRef provider;
CGImageRef myPngImage = CGImageCreateWithPNGDataProvider(provider, NULL, true, kCGRenderingIntentDefault);

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt: 72], kCGImagePropertyDPIHeight, [NSNumber numberWithInt: 72], kCGImagePropertyDPIWidth, nil];
CGImageDestinationRef destRef = CGImageDestinationCreateWithURL ((CFURLRef)outPath, (CFStringRef)@"image.png" , 1, NULL);
CGImageDestinationAddImage(destRef, myPngImage, (CFDictionaryRef)options);
CGImageDestinationFinalize(destRef);
CGRelease(destRef);

CGImageRelease(myColorMaskedImage);
CGImageRelease(myPngImage);

来自相当冗长的Quartz2d Programming Guidethis mailing list message

【讨论】:

    【解决方案2】:

    您可以尝试使起始 UIImage 完全透明,然后在其后面放置另一个完全白色的 UIImageView。

    【讨论】:

      【解决方案3】:

      您将不得不获取原始数据,查找白色像素,修改这些像素的 alpha 并保存到新的 NSData 对象,然后将其转换为 PNG。

      这并不难,但我不会说它微不足道。

      【讨论】:

        【解决方案4】:

        你可以试试这个

        extension UIImage {
            func imageByMakingWhiteBackgroundTransparent() -> UIImage? {
        
                let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
                let rawImageRef: CGImage = image.cgImage!
        
                let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
                UIGraphicsBeginImageContext(image.size);
        
                let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
                UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
                UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
                UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
                let result = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                return result
        
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2012-05-03
          • 2010-10-12
          • 2012-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          • 1970-01-01
          相关资源
          最近更新 更多