clip-masking uiview with CAShapeLayer and UIBezierPath

后端 未结 3 827
轻奢々
轻奢々 2021-01-04 21:10

I have a problem clipping a view using CAShapeLayer-UIBezierPath , I want to clip the content but I end up getting a stroke (frame) with that UIBezierPath , This is my code

3条回答
  •  余生分开走
    2021-01-04 21:44

    You can even improve @Eugene's response (greate work, mate!) with corner radius

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

提交回复
热议问题