How to add a blur mask with a custom shape above a

2019-03-16 13:00发布

问题:

I am using Swift to develop an iOS application with a camera feature, and it requires a blur layer above the camera view with a hole in the middle like the image shown below.

I have tried several methods, but none of them added the blur effect without covering the hole. I didn't find working solutions after spending time on Google as well.

Can anyone provide some hints on how can I only blur the non-transperant part of a png image that is attached to a image view?

Methods that I have tried:

  1. Use the built-in iOS 8 blur effect

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

    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 that I want to have:

回答1:

I've done this by creating an overlay with a layer with said blurred image, and then using a mask that is built from a path that goes all the way around the extents, and then jumps to the cutout hole, going the opposite direction with the winding fill rule.

Refer to documetation here:

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_paths/dq_paths.html

There are many documented examples of this though, here is one: drawing with clear color on UIView (cutting a hole) in static method