我有这个新的iOS 8 Swift项目,在其中一个视图控制器中我必须设置图像。但是,我想在将图像发送到视图之前使用CIFilter
更改图像的对比度:
所以这是我的代码:
view = UIImageView(frame:CGRectMake(0, 0, 200, 200))
var lecturePicture = UIImage(named: "placeholder")
var beginImage = lecturePicture?.CIImage
var controlsFilter = CIFilter(name: "CIColorControls")
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: "inputContrast")
var displayImage = UIImage(CIImage: controlsFilter.outputImage) // breakpoint
(view as UIImageView!).image = displayImage
好吧,我只是简单地获取一张图片,对其应用转换,然后将转换后的版本设为UIImage
并将其设置回我的视野。
但我只收到错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
有人可以告诉我这里我做错了什么吗?
答案 0 :(得分:5)
你几乎得到了它。
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey) // here you did it the right way
controlsFilter.setValue(1.5, forKey: "inputContrast") // you should keep the same approach here
Swift 2
let lecturePicture = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!)!)!
let controlsFilter = CIFilter(name: "CIColorControls")
let beginImage = CIImage(image: lecturePicture)
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: kCIInputContrastKey)
let displayImage = UIImage(CGImage: CIContext(options: nil).createCGImage(controlsFilter.outputImage, fromRect:controlsFilter.outputImage.extent()))!
displayImage
Swift 3或更高版本
let lecturePicture = UIImage(data: try! Data(contentsOf: URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!))!
let controlsFilter = CIFilter(name: "CIColorControls")!
let beginImage = CIImage(image: lecturePicture)
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: kCIInputContrastKey)
let displayImage = UIImage(cgImage: CIContext(options: nil).createCGImage(controlsFilter.outputImage!, from: controlsFilter.outputImage!.extent)!)
displayImage