How to add a blur mask with a custom shape over the dynamic camera view in Swift?

I use Swift to develop an iOS application with a camera function, and this requires a blur layer above the camera image with a hole in the middle, as shown in the image below.

I tried several methods, but none of them added a blur effect without covering the hole. I did not find working solutions, spending time on Google.

Can someone give some clues on how I can only erase the non-transperant portions of a PNG image that is attached to the image view?

Methods I tried:

  • Use iOS 8's native blur effect

    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    maskImage.addSubview(blurEffectView)
    
  • Use the filter "CIGaussianBlur"

    var imageToBlur = CIImage(image: image)
    var blurfilter = CIFilter(name: "CIGaussianBlur")
    blurfilter.setValue(imageToBlur, forKey: "inputImage")
    var resultImage = blurfilter.valueForKey("outputImage") as! CIImage
    var blurredImage = UIImage(CIImage: resultImage)
    self.maskImage.image = blurredImage
    

The visual effect I want to have is:

enter image description here

+4
source

All Articles