将 PNG 图像的背景从白色更改为透明 [英] Change a PNG image's background from white to transparent

查看:59
本文介绍了将 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

    }

}

这篇关于将 PNG 图像的背景从白色更改为透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆