Is programmatically inverting the colors of an image possible?

后端 未结 7 1895
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 07:00

I want to take an image and invert the colors in iOS.

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 07:35

    Updated to Swift 5 version of @MLBDG answer

    extension UIImage {
    func inverseImage(cgResult: Bool) -> UIImage? {
        let coreImage = self.ciImage
        guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
        filter.setValue(coreImage, forKey: kCIInputImageKey)
        guard let result = filter.value(forKey: kCIOutputImageKey) as? UIKit.CIImage else { return nil }
        if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
            return UIImage(cgImage: CIContext(options: nil).createCGImage(result, from: result.extent)!)
        }
        return UIImage(ciImage: result)
    }
    

    }

提交回复
热议问题