问题
I'm working on a simple app. It has an image view with pre-loaded image and a button. When pressed the button should invert the image in the image view.
It works the first time, but I expect it to invert the image back to its original form when I press the button again. However it crashes on this second press of the button.
Here is the relevant code from ViewController.swift
:
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var invertButton: UIButton!
@IBAction func invertButtonPressed(sender: UIButton) {
let beginImage = CIImage(image: imageView.image!)
let filter = CIFilter(name: "CIColorInvert")!
filter.setValue(beginImage, forKey: kCIInputImageKey)
imageView.image = UIImage(CIImage: (filter.outputImage)!)
}
Basically, beginImage
becomes nil
the second time around and I have no idea why. I have tried debugging by splitting those dense lines into as many let
assignments as I can but something mysteriously happens with that CIImage
constructor. Any ideas?
回答1:
The problem is this line:
imageView.image = UIImage(CIImage: (filter.outputImage)!)
You can't do that. A CIImage does not magically turn into a UIImage. An image view needs a bitmap-based image, not a CIImage-based image. You have to render the CIImage to turn it into a UIImage, either by getting a CIContext and telling it to create CGImage or by drawing the CIImage into a graphics context.
来源:https://stackoverflow.com/questions/32875114/why-cant-i-invert-my-image-back-to-original-with-cifilter-in-my-swift-ios-app