【问题标题】:Change a PNG image's background from white to transparent将 PNG 图像的背景从白色更改为透明
【发布时间】:2016-08-15 19:04:39
【问题描述】:

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

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

这是我的代码:

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 中尝试了不同的选项,但没有成功。

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

我的 iOS 模拟器截图:

【问题讨论】:

  • 您需要更改图像,去除白色背景并使其透明。
  • 感谢您的快速回复,我只有png图像,我可以将其更改为透明背景吗?我没有矢量文件。
  • 是的,您可以使用图像编辑程序来做到这一点,但可能没那么容易。
  • 这不是完全 trasperenat 图像,因为@rckoenes 说您需要从图像中删除白色
  • This 可能是您最不想尝试的事情。

标签: ios uiimageview


【解决方案1】:

当您的背景颜色为白色时,此代码将起作用,根据您的需要更改颜色值

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

    }

}

【讨论】:

  • Swift 5,iOS 14 仍然完美运行!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 2021-03-28
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多