-1

[I'm in the process of learning of Swift Development. Last time I've tried to add a blur for a picture of Ronald Reagan. First I found UIBlurEffect method, but it wasn't exactly what I expected. Then I tried to use CIFilter method. I walked through horrible way of implementing CIGaussianBlur, but eventually I made it! Then I looked into storyboard, and I found out that picture was scaled and marked with white bezels (as you can see on attached pic). What I did wrong? What should I do? Is there more simple way to add blur on a photo programmatically? I know there is a way to do that by third side apps like Adobe PS, but I want to have it in code. :)

import UIKit

@IBDesignable
class blurImageView: UIImageView {

    override func awakeFromNib() {
        super.awakeFromNib()
        applyBlurEffect(image: image!)
    }
    
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        applyBlurEffect(image: image!)
    }
    
    func applyBlurEffect(image: UIImage){
        
        if self.image != nil {
        let imageToBlur = CIImage(image: image)
        let blurfilter = CIFilter(name: "CIGaussianBlur")!
        blurfilter.setValue(imageToBlur, forKey: "inputImage")
        let resultImage = blurfilter.value(forKey: "outputImage") as! CIImage
        let blurredImage = UIImage(ciImage: resultImage)
            self.image = blurredImage
        
        }
    }
}

enter image description here

Czkii
  • 53
  • 4

1 Answers1

0

Welcome!

CIGaussianBlur (and other convolution filters from Core Image) will increase the extent of an image by a region that depends on the size of the blur.

You can simply crop to the extent of the input image to get rid of that margin:

let blurredImage = UIImage(ciImage: resultImage.cropped(to: imageToBlur.extent))

By the way, I recommend that you import CoreImage.CIFilterBuiltins. This will give you a nice type-safe interface to most Core Image filters:

let input = CIImage(image: image)!
let blurFilter = CIFilter.gaussianBlur()
blurFilter.inputImage = input
blurFilter.radius = 10
let output = blurFilter.outputImage?.cropped(to: input.extent)
self.image = UIImage(ciImage: output!)
Frank Rupprecht
  • 9,191
  • 31
  • 56