简体   繁体   中英

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

For reference:

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM