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

独自空忆成欢 提交于 2019-12-20 14:41:41

问题


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



来源:https://stackoverflow.com/questions/31662931/how-to-add-a-blur-mask-with-a-custom-shape-above-a-dynamic-camera-view-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!