1234
1234

Reputation: 579

Change a PNG image's background from white to transparent

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.

Note: my parent view color can be different colours. (not just white)

Here is my code:

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];

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

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

enter image description here

My iOS simulator screenshot: enter image description here

Upvotes: 1

Views: 2010

Answers (1)

Jagveer Singh
Jagveer Singh

Reputation: 2318

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

    }

}

Upvotes: 5

Related Questions