Joe Joe - 1 month ago 10
Swift Question

Control ciFilter using slider in Swift

I am trying to achieve a blur effect using CIBoxBlur filter on imageView.I am using UISlider to control the blur value.Blur effect works when,I increment the slider value. I can clearly see the blur value applying to imageView.But, when i
decrement the slider value blur been applying more deeper into my imageView.ImageView not going back to normal.I know why is happening.but i am not sure how to fix it.

@IBOutlet weak var blur: UISlider!

@IBAction func blurSlider(_ sender: UISlider) {

let currentValue = Int(sender.value)
blur.maximumValue = 5
blur.minimumValue = 0

let currentFilter = CIFilter(name: "CIBoxBlur")
currentFilter!.setValue(CIImage(image: imageView.image!), forKey: kCIInputImageKey)
currentFilter!.setValue(currentValue, forKey: kCIInputRadiusKey)

let cropFilter = CIFilter(name: "CICrop")
cropFilter!.setValue(currentFilter!.outputImage, forKey: kCIInputImageKey)
cropFilter!.setValue(CIVector(cgRect: (CIImage(image: imageView.image!)?.extent)!), forKey: "inputRectangle")

let output = cropFilter!.outputImage
let cgimg = context.createCGImage(output!, from: output!.extent)
let processedImage = UIImage(cgImage: cgimg!)
imageView.image = processedImage

}


Thanks in Advance.

Answer

Its pretty simple. You can apply the filter on the original image instead of the already filtered image. This code will help.

@IBAction func blurSlider(_ sender: UISlider) {
    let originalImage = UIImage(named: "yourimage")// replace yourimage with the name of your image
    let currentValue = Int(sender.value)

    blur.maximumValue = 5
    blur.minimumValue = 0

    let currentFilter = CIFilter(name: "CIBoxBlur")
    currentFilter!.setValue(CIImage(image: originalImage!), forKey: kCIInputImageKey)
    currentFilter!.setValue(currentValue, forKey: kCIInputRadiusKey)

    let cropFilter = CIFilter(name: "CICrop")
    cropFilter!.setValue(currentFilter!.outputImage, forKey: kCIInputImageKey)
    cropFilter!.setValue(CIVector(cgRect: (CIImage(image: originalImage!)?.extent)!), forKey: "inputRectangle")

    let output = cropFilter!.outputImage
    let cgimg = context.createCGImage(output!, from: output!.extent)
    let processedImage = UIImage(cgImage: cgimg!)
    imageView.image = processedImage

}