How to create an inverted colour (Negative of an image) UIImage using Swift

251 Views Asked by At

For reference:

The left image would be the end result of the one on the right.

enter image description here

1

There are 1 best solutions below

0
Prateek Raj On

I have scoured the internet for a better way to deal with this issue, Ofcourse i have found couple of bits and pieces here and there but not exactly what i was looking for so here is an easy one to use with the Swift-5 support.

extension UIImage {
    var negative: UIImage? {
        let context = CIContext(options: nil)
        guard let currentFilter = CIFilter(name: "CIColorInvert") else { return nil }
        currentFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
        if let output = currentFilter.outputImage,
           let cgImage = context.createCGImage(output, from: output.extent) {
            return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
        }
        return nil
    }
}

and ofcourse the usage willbe easy image.negative