1

I am using this code to create a layer with a transparent hole

let radius = min(self.view.frame.size.width,self.view.frame.size.height)
    print(radius)
    let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), cornerRadius: 0)
    let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: self.view.frame.size.height/2 - radius/2 , width: radius, height: radius), cornerRadius: radius/2)
    path.append(circlePath)

    path.usesEvenOddFillRule = true

    fillLayer.path = path.cgPath
    fillLayer.fillRule = kCAFillRuleEvenOdd
    fillLayer.fillColor = UIColor.black.cgColor
    fillLayer.opacity = 0.5
    view.layer.addSublayer(fillLayer)

it works fine if the initial view is portrait or landscape as show in the image

enter image description here

However if the view changes from portrait to landscape or landscape to portrait

The layer is not properly oriented as shown

enter image description here

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Ahmed
  • 1,229
  • 2
  • 20
  • 45

1 Answers1

1

It looks like you'll need to update the frame of your path whenever the user rotates their device. You're looking for something like the answer here.

If you need to animate along with the transition, try something like this:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { context in            
        // update frames here
    }, completion: nil)
}
Chris Hansen
  • 103
  • 4