为什么我不能在我的Swift iOS应用程序中使用CIFilter将我的图像反转回原始图像 [英] Why can't I invert my image back to original with CIFilter in my Swift iOS app
问题描述
我正在开发一个简单的应用程序。
它有一个带有预加载图像和按钮的图像视图。
按下按钮时,应该反转图像视图中的图像。
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.
以下是来自 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)!)
}
基本上, beginImage
变成 nil
第二个时间到了,我不明白为什么。我已经尝试通过将那些密集线分成尽可能多的让
赋值进行调试,但是 CIImage
神秘地发生了一些事情。构造函数。有什么想法?
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?
推荐答案
问题是这一行:
imageView.image = UIImage(CIImage: (filter.outputImage)!)
<你不能这样做。 CIImage并没有神奇地变成UIImage。图像视图需要基于位图的图像,而不是基于CIImage的图像。您必须渲染 CIImage才能将其转换为UIImage,方法是获取CIContext并告诉它创建CGImage或将CIImage绘制到图形上下文中。
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.
这篇关于为什么我不能在我的Swift iOS应用程序中使用CIFilter将我的图像反转回原始图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!