iOS invert mask in drawRect

前端 未结 7 2025
名媛妹妹
名媛妹妹 2020-12-08 07:54

With the code below, I am successfully masking part of my drawing, but it\'s the inverse of what I want masked. This masks the inner portion of the drawing, where I would li

7条回答
  •  难免孤独
    2020-12-08 08:20

    Swift 5

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let red = UIView(frame: view.bounds)
            view.addSubview(red)
            view.backgroundColor = UIColor.cyan
            red.backgroundColor = UIColor.red
            red.mask(CGRect(x: 50, y: 50, width: 50, height: 50), invert: true)
        }
    }
    
    extension UIView{
    
        func mask(_ rect: CGRect, invert: Bool = false) {
            let maskLayer = CAShapeLayer()
            let path = CGMutablePath()
            if (invert) {
                path.addRect(bounds)
            }
            path.addRect(rect)
            maskLayer.path = path
            if (invert) {
                maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
            }
            // Set the mask of the view.
            layer.mask = maskLayer
        }
    }
    

    Thanks @arvidurs

提交回复
热议问题