4

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
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Koh
  • 2,687
  • 1
  • 22
  • 62
  • i dont have any idea... but the last line should not be there blurView.layer.mask = scanLayer – Naresh Sep 16 '17 at 12:08
  • use this https://stackoverflow.com/questions/29647792/swift-how-to-create-a-view-with-a-shape-cropped-in-it see Dănuț Mihai Florian's answer – Naresh Sep 16 '17 at 12:10

1 Answers1

10

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
Vitaly Migunov
  • 4,297
  • 2
  • 19
  • 23
  • This solution worked! But I don understand the concept. Why is there a need to have superlayerPath? – Koh Sep 16 '17 at 12:35
  • Because you need to mask everything around the inner rectangle but not the rectangle itself. You can add this line in order to see how the mask working let superlayerPath = UIBezierPath.init(ovalIn: blurView.frame) – Vitaly Migunov Sep 16 '17 at 12:39
  • Thanks great ans.Now i want to add shadow on that cut out area.How can it possible.please help me. @VitalyMigunov – Yogendra Patel Jan 02 '18 at 04:44
  • 1
    This is a topic for new question @YogendraPatel – Vitaly Migunov Jan 02 '18 at 04:56