Swift version: 5.6
One of the most useful filters to have in your toolbox is called CIColorMonochrome
, and its job is to remove the color variance from an image then tint it however you want. If you use gray as your tint color, it produces plain black and white images, but you can also use other colors to get sepia tone and other effects.
Here’s some example code to get you started:
guard let currentCGImage = yourUIImage.cgImage else { return }
let currentCIImage = CIImage(cgImage: currentCGImage)
let filter = CIFilter(name: "CIColorMonochrome")
filter?.setValue(currentCIImage, forKey: "inputImage")
// set a gray value for the tint color
filter?.setValue(CIColor(red: 0.7, green: 0.7, blue: 0.7), forKey: "inputColor")
filter?.setValue(1.0, forKey: "inputIntensity")
guard let outputImage = filter?.outputImage else { return }
let context = CIContext()
if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
let processedImage = UIImage(cgImage: cgimg)
print(processedImage.size)
}
To make that work you’ll need a UIImage
called yourUIImage
, then replace the print(processedImage.size)
line at the end with whatever you want to do with your black and white image.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 6.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.