Why can't I invert my image back to original with CIFilter in my Swift iOS app

旧街凉风 提交于 2019-11-26 18:42:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!