How to draw CALayer border around its mask?

后端 未结 6 1535
谎友^
谎友^ 2021-02-07 09:39

So, I have a CALayer, which has a mask & I want to add border around this layer\'s mask. For example, I have set triangle mask to the layer and I want to have b

6条回答
  •  面向向阳花
    2021-02-07 10:05

    My approach in swift3.

    // Usage:
    self.btnGroup.roundCorner([.topRight, .bottomRight], radius: 4.0, borderColor: UIColor.red, borderWidth: 1.0)
    
    // Apply round corner and border. An extension method of UIView.
    public func roundCorner(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        let path = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    
        let borderPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let borderLayer = CAShapeLayer()
        borderLayer.path = borderPath.cgPath
        borderLayer.lineWidth = borderWidth
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.frame = self.bounds
        self.layer.addSublayer(borderLayer)
    }
    

提交回复
热议问题