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

前端 未结 11 1889
自闭症患者
自闭症患者 2020-12-28 16:48

The setup is simple.

  • A ViewController with UIImageView that has an image assigned.
  • A UIButton that when clicked blurs the image in the UIImageView.<
11条回答
  •  孤城傲影
    2020-12-28 17:25

    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:

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

提交回复
热议问题