I'm taking a snapshot of a subview and turning it into an image:
let image = UIImage(view: swiftyDraw)
let scaledImage = scaleImage(image: image, toSize: CGSize(width: 28, height:28))
finalImage is a UIImageView
and setting it to display the scaledImage works, I can see it fine:
finalImage.image = scaledImage //this works
However, I want to invert the colors before displaying it:
let filter = CIFilter(name: "CIColorInvert")
filter!.setValue(CIImage(image: scaledImage), forKey: kCIInputImageKey)
let invertedImage = UIImage(ciImage: filter!.outputImage!)
finalImage.image = invertedImage //this does not work
Nothing shows up when I set finalImage.image to invertedImage, but it shows up fine when it's set to scaledImage.
Edit: scaleImage function:
func scaleImage (image: UIImage, toSize size:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Let's say your "scaledImage" is an UIImage
, so you can directly get an CIImage
without creating a new one.
guard let ciImage = scaledImage.ciImage, let filter = CIFilter(name: "CIColorInvert") else {
fatalError("CIImage conversion fail")
}
//Now access the CIFilter object to filter the image
filter.setValue(ciImage, forKey: kCIInputImageKey)
finalImage.image = UIImage(ciImage: filter.outputImage!)
Update
In case, if you are fatalError
means UIImage
doesn't exists with CIImage
so you need to convert UIImage
to CIImage
.
extension UIImage {
var toCIImage: CIImage {
return self.CIImage ?? CIImage(CGImage: self.CGImage!)
}
}
guard let filter = CIFilter(name: "CIColorInvert") else {
fatalError("CIImage conversion fail")
}
let ciImage = scaledImage.toCIImage
//Now access the CIFilter object to filter the image
filter.setValue(ciImage, forKey: kCIInputImageKey)
finalImage.image = UIImage(ciImage: filter.outputImage!)