1

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

Dave Wood
  • 13,143
  • 2
  • 59
  • 67
1234
  • 539
  • 3
  • 12
  • You will need to change the image, remove the white background and make it transparent. – rckoenes Apr 22 '16 at 08:44
  • Thanks for the quick reply, I only have png image, can I change it to transparent background? I don't have the vector file. – 1234 Apr 22 '16 at 08:45
  • Yes you can use a image editing program to do that, but it might not be that easy. – rckoenes Apr 22 '16 at 08:47
  • this is not fully trasperenat image as @rckoenes said you need to remove the white color from your image – Nitin Gohel Apr 22 '16 at 09:04
  • [This](http://stackoverflow.com/questions/633722/how-to-make-one-color-transparent-on-a-uiimage) might be the last thing you want to try. – zc246 Apr 22 '16 at 10:04

1 Answers1

5

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

    }

}
Jagveer Singh
  • 2,258
  • 19
  • 34