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

时间:2016-04-22 08:36:21

标签: ios uiimageview

我有一个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];

enter image description here

我的iOS模拟器截图: enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

    }

}
相关问题