iosswiftuiimageviewcifilterciimage

How to blur an existing image in a UIImageView with Swift?


The setup is simple.

Storyboard

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var bg: UIImageView!

    @IBAction func blur(_ sender: Any) {
        let inputImage = CIImage(cgImage: (bg.image?.cgImage)!)

        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(inputImage, forKey: "inputImage")
        filter?.setValue(10, forKey: "inputRadius")
        let blurred = filter?.outputImage
        bg.image = UIImage(ciImage: blurred!)
    }
}

When the button is clicked the screen just turns white. Can't figure out what I'm doing wrong. Anyone know what I'm doing wrong?


Solution

  • You could simply use UIVisualEffect to achieve blur effect. As you trying to achieve a blur effect using CoreImage.Try below code after import CoreImage to your class.

    var context = CIContext(options: nil)
    
    func blurEffect() {
    
        let currentFilter = CIFilter(name: "CIGaussianBlur") 
        let beginImage = CIImage(image: bg.image!)
        currentFilter!.setValue(beginImage, forKey: kCIInputImageKey)
        currentFilter!.setValue(10, forKey: kCIInputRadiusKey)
    
        let cropFilter = CIFilter(name: "CICrop")
        cropFilter!.setValue(currentFilter!.outputImage, forKey: kCIInputImageKey)
        cropFilter!.setValue(CIVector(cgRect: beginImage!.extent), forKey: "inputRectangle")
    
        let output = cropFilter!.outputImage 
        let cgimg = context.createCGImage(output!, from: output!.extent)
        let processedImage = UIImage(cgImage: cgimg!)
        bg.image = processedImage
    }
    

    Output:

    enter image description here

    Note: I recommend you to test the code in real device as Simulator performance is too slow on coreImage.