将 PNG 图像的背景从白色更改为透明

问题描述:

我有一个 PNG 图像文件,我正在使用 UIImageView 在视图中显示图像.我想将图像中的白色更改为透明.

I have a PNG image file and I'm using a UIImageView to show the image in a view. I want to change the white color to transparent in my image.

注意:我的父视图颜色可以是不同的颜色.(不只是白色)

这是我的代码:

UIImageView* oriImageView = [[UIImageView alloc]initWithFrame:originalFrame];
UIImage* oriImage = [UIImage imageNamed:@"tap.png"];
oriImageView.layer.opacity = 0.5f;
oriImageView.backgroundColor = [UIColor clearColor];
oriImageView.opaque = NO;
oriImageView.tintColor = [UIColor clearColor];
oriImageView.image = oriImage;
[self.view addSubview:oriImageView];

我在 SO 中尝试了以下不同的选项,但没有运气.

I have tried different options in SO as following with no luck.

oriImageView.backgroundColor = [UIColor clearColor];
oriImageView.opaque = NO;
oriImageView.tintColor = [UIColor clearColor];

我的iOS模拟器截图:

My iOS simulator screenshot:

当你的背景颜色是白色时,这段代码会起作用,根据你的需要改变颜色值

this code will work when your background color is white, change color value according to your need

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

    }

}