Round top corners of a UIView and add border

前端 未结 4 494
自闭症患者
自闭症患者 2020-12-03 01:55

I have the following code in a category that does rounding of corners. I would also like to draw a border. But the border is not shown on the rounded part of the corner.

4条回答
  •  春和景丽
    2020-12-03 02:18

    this is probably a very late answer but I would just like to share the solution I came up with based on answers of different people from different similar questions. I got big help from Vojtech's answer above.

    extension UIView {
        func EZRoundCorners(corners:UIRectCorner, radius: CGFloat) -> CAShapeLayer {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.CGPath
            self.layer.mask = mask
            return mask
        }
    
        func EZRoundCornersWithBorder(corners:UIRectCorner, radius:CGFloat, color:UIColor, width:CGFloat) -> CAShapeLayer {
    
            let mask = self.EZRoundCorners(corners, radius: radius)
    
            // Add border
            let borderLayer = EZCALayer()
            borderLayer.path = mask.path // Reuse the Bezier path
            borderLayer.fillColor = UIColor.clearColor().CGColor
            borderLayer.strokeColor = color.CGColor
            borderLayer.lineWidth = width
            borderLayer.frame = self.bounds
            self.layer.addSublayer(borderLayer)
            return borderLayer
        }
    
        func removeEZLayers () {
            for layer in self.layer.sublayers! {
                if layer is EZCALayer {
                    layer.removeFromSuperlayer()
                }
            }
        }
    }
    
    class EZCALayer : CAShapeLayer {
    }
    

    I inherited from CAShapeLayer so I can remove the border sublayers if I don't want to use them anymore.

提交回复
热议问题