Creating a blurView with a clear cut out

1.3k views Asked by At

I am creating an overlay of blurredView with a clear rectangle cutout in the middle. My code so far has achieved the opposite, ie a clearView with a blur cutout in the middle instead.

I have adapted my steps from the following posts, I appreciate if anyone could point me in the right direction.

Swift mask of circle layer over UIView

CALayer with transparent hole in it

let blurView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
blurView.effect = UIBlurEffect(style: UIBlurEffectStyle.dark)

let scanLayer = CAShapeLayer()
scanLayer.path = CGPath(rect: scanRect, transform: nil)

view.addSubview(blurView)
blurView.layer.addSublayer(scanLayer)
blurView.layer.mask = scanLayer
1

There are 1 answers

4
Vitaly Migunov On BEST ANSWER

You can do it like this

    let scanLayer = CAShapeLayer()

    let scanRect = CGRect.init(x: 100, y: 100, width: 200, height: 100)

    let outerPath = UIBezierPath(rect: scanRect)

    let superlayerPath = UIBezierPath.init(rect: blurView.frame)
    outerPath.usesEvenOddFillRule = true
    outerPath.append(superlayerPath)
    scanLayer.path = outerPath.cgPath
    scanLayer.fillRule = kCAFillRuleEvenOdd
    scanLayer.fillColor = UIColor.black.cgColor

    view.addSubview(blurView)
    blurView.layer.mask = scanLayer