How can I change the saturation of an UIImage?

后端 未结 6 1650
旧巷少年郎
旧巷少年郎 2021-01-30 05:42

I have an UIImage and want to shift it\'s saturation about +10%. Are there standard methods or functions that can be used for this?

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 06:14

    Swift 5

    extension UIImage {
        
        func withSaturationAdjustment(byVal: CGFloat) -> UIImage {
            guard let cgImage = self.cgImage else { return self }
            guard let filter = CIFilter(name: "CIColorControls") else { return self }
            filter.setValue(CIImage(cgImage: cgImage), forKey: kCIInputImageKey)
            filter.setValue(byVal, forKey: kCIInputSaturationKey)
            guard let result = filter.value(forKey: kCIOutputImageKey) as? CIImage else { return self }
            guard let newCgImage = CIContext(options: nil).createCGImage(result, from: result.extent) else { return self }
            return UIImage(cgImage: newCgImage, scale: UIScreen.main.scale, orientation: imageOrientation)
        }
    
    }
    

提交回复
热议问题