Crop a CAShapeLayer retrieving the external path

后端 未结 2 683
盖世英雄少女心
盖世英雄少女心 2020-12-02 19:38

I am trying to crop a layer with other, but, instead of creating a mask (B) and crop the layer (A) getting a cropped layer A with the shape of B, I want to get a layer with

2条回答
  •  攒了一身酷
    2020-12-02 20:07

    Swift 3.0 solution:

    class MakeTransparentHoleOnOverlayView: UIView {
    
        @IBOutlet weak var transparentHoleView: UIView!
    
        // MARK: - Drawing
    
        override func draw(_ rect: CGRect) {
            super.draw(rect)
    
            if self.transparentHoleView != nil {
                // Ensures to use the current background color to set the filling color
                self.backgroundColor?.setFill()
                UIRectFill(rect)
    
                let layer = CAShapeLayer()
                let path = CGMutablePath()
    
                // Make hole in view's overlay
                // NOTE: Here, instead of using the transparentHoleView UIView we could use a specific CFRect location instead...
                path.addRect(transparentHoleView.frame)
                path.addRect(bounds)
    
                layer.path = path
                layer.fillRule = kCAFillRuleEvenOdd
                self.layer.mask = layer
            }
        }
    
        override func layoutSubviews () {
            super.layoutSubviews()
        }
    
        // MARK: - Initialization
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
    }
    

提交回复
热议问题