Simply mask a UIView with a rectangle

前端 未结 7 1486
别跟我提以往
别跟我提以往 2020-11-30 20:10

I want to know how to simply mask the visible area of a UIView of any kind. All the answers/tutorials I\'ve read so far describe masking with an image, gradient or creating

7条回答
  •  感动是毒
    2020-11-30 20:35

    Thanks for answers guys.

    In case someone can't find suitable answer on SO for this question for hours, like i just did, i've assembled a working gist in Swift 2.2 for masking/clipping UIView with CGRect/UIBezierPath:

    https://gist.github.com/Flar49/7e977e81f1d2827f5fcd5c6c6a3c3d94

    extension UIView {
    
        func mask(withRect rect: CGRect, inverse: Bool = false) {
            let path = UIBezierPath(rect: rect)
            let maskLayer = CAShapeLayer()
    
            if inverse {
                path.append(UIBezierPath(rect: self.bounds))
                maskLayer.fillRule = kCAFillRuleEvenOdd
            }
    
            maskLayer.path = path.cgPath
    
            self.layer.mask = maskLayer
        }
    
        func mask(withPath path: UIBezierPath, inverse: Bool = false) {
            let path = path
            let maskLayer = CAShapeLayer()
    
            if inverse {
                path.append(UIBezierPath(rect: self.bounds))
                maskLayer.fillRule = kCAFillRuleEvenOdd
            }
    
            maskLayer.path = path.cgPath
    
            self.layer.mask = maskLayer
        }
    }
    

    Usage:

    let viewSize = targetView.bounds.size
    let rect = CGRect(x: 20, y: 20, width: viewSize.width - 20*2, height: viewSize.height - 20*2)
    
    // Cuts rectangle inside view, leaving 20pt borders around
    targetView.mask(withRect: rect, inverse: true)
    
    // Cuts 20pt borders around the view, keeping part inside rect intact
    targetView.mask(withRect: rect)
    

    Hope it will save someone some time in the future :)

提交回复
热议问题