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

前端 未结 11 1969
自闭症患者
自闭症患者 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:33

    Here is how I got my expected result in SWIFT 3.1: Hope it will help.

    func blurImage(image:UIImage) -> UIImage? {
            let context = CIContext(options: nil)
            let inputImage = CIImage(image: image)
            let originalOrientation = image.imageOrientation
            let originalScale = image.scale
    
            let filter = CIFilter(name: "CIGaussianBlur")
            filter?.setValue(inputImage, forKey: kCIInputImageKey)
            filter?.setValue(10.0, forKey: kCIInputRadiusKey) 
            let outputImage = filter?.outputImage
    
            var cgImage:CGImage?
    
            if let asd = outputImage
            {
                cgImage = context.createCGImage(asd, from: (inputImage?.extent)!)
            }
    
            if let cgImageA = cgImage
            {
                return UIImage(cgImage: cgImageA, scale: originalScale, orientation: originalOrientation)
            }
    
            return nil
        }
    

提交回复
热议问题