Swift - How to create a view with a shape cropped in it

后端 未结 5 2087
盖世英雄少女心
盖世英雄少女心 2021-01-04 10:00

I\'m trying to achieve the result shown in the image using swift 1.2 and xcode 6.

Basically I want to create a view with a shape cut in it to be able to see the the

5条回答
  •  礼貌的吻别
    2021-01-04 10:27

    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)
        }
    }
    

提交回复
热议问题