-1

I have a UIIMageView inside the view of a UIVIewController. I have drawn a rectangle - UIBezierPath in the layer of the root view and I would like to fill just the outside of the rectangle and leave the inside of the rectangle unfilled so that one can see through to the image below it. Below is my attempt but it fills the rectangle and not the outside of the rectangle.

 let rectHoleSize = CGRect.init(x: myRectangle.frame.minX, y: myRectangle.frame.minY, width: myRectangle.frame.width, height: myRectangle.frame.height)

    let path = UIBezierPath.init(rect: rectHoleSize)
    path.usesEvenOddFillRule = true

    let layer = CAShapeLayer()
    layer.path = path.cgPath
    layer.fillRule = .evenOdd
    layer.fillColor = view.backgroundColor?.cgColor
    layer.opacity = 0.5
    view.layer.addSublayer(layer)
jamesMcKey
  • 481
  • 5
  • 28

1 Answers1

0

You would need to use a mask. Place a filled layer on top of the image view and punch a hole in the filled layer with a mask (which can be a shape layer).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • please could you expand with answer in code. I have tried adding a mask to view and view.layer.mask but i am just getting a black sreen – jamesMcKey Jul 05 '19 at 22:20
  • I don't think the world of Stack Overflow needs yet another answer explaining how to use a mask to punch a hole in something. And I personally have explained it too many times already. Here's one: https://stackoverflow.com/a/23452614/341994 – matt Jul 05 '19 at 22:23
  • i referred to your swift answer (function cut()), but the hole punched is black. i would like the hole to see through to the image. – jamesMcKey Jul 05 '19 at 22:34
  • Well then you're not doing what I said. – matt Jul 05 '19 at 22:38