CAShapeLayer with border and fill color and rounding

前端 未结 3 1946
长发绾君心
长发绾君心 2021-02-20 06:48

How do I use CAShapeLayer to draw a line that has both a border color, border width and fill color?

Here\'s what I\'ve tried, but it\'s only ever blue...



        
3条回答
  •  我寻月下人不归
    2021-02-20 07:25

    In Swift 3. an extension method of UIView.

    // 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)
    }
    

提交回复
热议问题