Search code examples
iosswiftxcodeuser-interfaceconstraints

Swift mask UIView constraints issues


I've created a mask view for my camera screen that blurs everything except for a small rectangle in the middle. I'm having issues when testing on different screen sizes. I'm testing on an 11 Pro and an 8. If my storyboard view has the proper device selected, the constraints look fine on the device. But if I switch phones without changing in the storyboard, it is incorrect. I'm programmatically creating the mask view. Any help would be much appreciated!

func setupBlur() {
    if !UIAccessibility.isReduceTransparencyEnabled {

        blurView.backgroundColor = .clear

        let blurEffect = UIBlurEffect(style: .dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)

        blurEffectView.frame = blurView.bounds
        blurEffectView.translatesAutoresizingMaskIntoConstraints = false

        blurEffectView.addConstraints(blurView.constraints)
        blurView.addSubview(blurEffectView)


        let maskView = UIView(frame: blurView.bounds)
        maskView.translatesAutoresizingMaskIntoConstraints = false
        maskView.addConstraints(blurView.constraints)
        maskView.backgroundColor = .clear
        let outerbezierPath = UIBezierPath.init(rect: blurView.bounds)

        let croppedOriginX = (blurView.bounds.width / 2) - (captureView.bounds.width / 2)
        let croppedOriginY = (blurView.bounds.height / 2) - (captureView.bounds.height / 2)
        let frame = CGRect(x: croppedOriginX, y: croppedOriginY, width: captureView.bounds.width, height: captureView.bounds.height)

        let innerRectPath = UIBezierPath.init(rect: frame)
        outerbezierPath.append(innerRectPath)
        outerbezierPath.usesEvenOddFillRule = true

        let fillLayer = CAShapeLayer()
        fillLayer.fillRule = kCAFillRuleEvenOdd
        fillLayer.fillColor = UIColor.green.cgColor // any opaque color would work
        fillLayer.path = outerbezierPath.cgPath
        maskView.layer.addSublayer(fillLayer)

        blurView.mask = maskView;

    }
}

enter image description here

enter image description here


Solution

  • override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.setupBlur()
    }