iOS镂空效果

直接再View上做镂空效果,代码 如下:

extension UIView {
// 不带圆角,方形
func mask(maskRect: CGRect, invert: Bool = false) {

        let maskLayer = CAShapeLayer()

        let path = CGMutablePath()

        if (invert) {

            path.addRect(self.bounds)

        }

        path.addRect(maskRect)

        

        maskLayer.path = path

        if (invert) {

            maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        }

        // Set the mask of the view.

        self.layer.mask = maskLayer;

    }

    
//带圆角
    func mask(withRect maskRect: CGRect, cornerRadius: CGFloat, inverse: Bool = false) {

        let maskLayer = CAShapeLayer()

        let path = CGMutablePath()

        if (inverse) {

            path.addRect(self.bounds)

        }

        path.addPath(UIBezierPath(roundedRect: maskRect, cornerRadius: cornerRadius).cgPath)

        maskLayer.path = path

        if (inverse) {

            maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        }

        self.layer.mask = maskLayer;

    }
}

效果如下图:

 iOS镂空效果_第1张图片

 

你可能感兴趣的:(iOS,iOS)