invert white to black uiimage

Swift

Using CIContext instead of -UIImage:CIImage (see https://stackoverflow.com/a/28386697/218152), and building upon @wtznc's response, here is a self-contained IBDesignable:

@IBDesignable
class InvertImage: UIImageView {

    @IBInspectable var originalImage:UIImage? = nil

    @IBInspectable var invert:Bool = false {
        didSet {
            var inverted = false
            if let originalImage = self.originalImage {
                if(invert) {
                    let image = CIImage(CGImage: originalImage.CGImage!)
                    if let filter = CIFilter(name: "CIColorInvert") {
                        filter.setDefaults()
                        filter.setValue(image, forKey: kCIInputImageKey)
                        
                        let context = CIContext(options: nil)
                        let imageRef = context.createCGImage(filter.outputImage!, fromRect: image.extent)
                        self.image = UIImage(CGImage: imageRef)
                        inverted = true
                    }
                }
            }
            
            if(!inverted) {
                self.image = self.originalImage
            }
        }
    }
}

To use it, set Original Image instead of Image since Image will be dynamically associated:

enter image description here


Swift3

extension UIImage {
    func invertedImage() -> UIImage? {
        guard let cgImage = self.cgImage else { return nil }
        let ciImage = CoreImage.CIImage(cgImage: cgImage)
        guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
        filter.setDefaults()
        filter.setValue(ciImage, forKey: kCIInputImageKey)
        let context = CIContext(options: nil)
        guard let outputImage = filter.outputImage else { return nil }
        guard let outputImageCopy = context.createCGImage(outputImage, from: outputImage.extent) else { return nil }
        return UIImage(cgImage: outputImageCopy, scale: self.scale, orientation: .up) 
    }
}

Firstly, you have to add the Core Image framework to your project.

Project settings -> Targets "project name" -> Build phases -> Link Binary With Libraries -> Add items -> CoreImage.framework

enter image description here Secondly, import the Core Image header to your implementation file.

#import <CoreImage/CoreImage.h>

Initialize an UIImage object to store the original file.

UIImage *inputImage = [UIImage imageNamed:@"imageNamed"];

Create a CIFilter to define how you want to modify your original UIImage object.

CIFilter* filter = [CIFilter filterWithName:@"CIColorInvert"];
[filter setDefaults];
[filter setValue:inputImage.CIImage forKey:@"inputImage"];

Create another UIImage object to keep modified image.

UIImage *outputImage = [[UIImage alloc] initWithCIImage:filter.outputImage];

Voilà! Hope it will help.