my problem is as follows: I made a simple app with a uiviewcontroller and an uiview(FilterView). om my view I added a UIButton and a UIImageView. What I want is that when you push the button a SepiaFilter is applied to the image:
func sepiaButtonClicked( sender:UIButton ){
let context = CIContext(options: nil)
let image = CIImage(image: theView.imageView.image)
let filter = CIFilter(name: "CISepiaTone", withInputParameters: [
kCIInputImageKey : image,
kCIInputIntensityKey : NSNumber(double: 0.5)
])
let imageWithFilter = filter.outputImage
theView.imageView.image = UIImage(CIImage: imageWithFilter)
}
theView refers to the UIView with this piece of code on top
var theView:FilterView {
get {
return view as! FilterView
}
}
now when I push the button the filter is applied as I wanted it to happen, but if you would press it again afterwards it gives a fatal error 'unexpectedly found nil while unwrapping an Optional value'. this is I think the image ( the one I enter for kCIInputImageKey ).
Can anyone give me an explanation on why this is happening? I can't figure out the difference between the first and second click on the button.. how I see it this code just replaces the UIImage with the new one and it should be ready to be triggered again?
Thx in advance,
Pieter-Jan De Bruyne
Try this :
func sepiaButtonClicked( sender:UIButton ){
var CurrentImage = self.imageView.image
var inputImage = CIImage(image:CurrentImage)
let filter = CIFilter(name:"CISepiaTone")
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(0.5, forKey: kCIInputIntensityKey)
let context = CIContext(options: nil)
let imageWithFilter = filter.outputImage
let NewOuptutImage = context.createCGImage(imageWithFilter , fromRect: imageWithFilter.extent())
imageView.image = UIImage(CGImage: NewOuptutImage)
}