在 UIView 周围绘制 CALayer 边框

Draw CALayer border around UIView

我想在圆形 UIView 周围绘制一个带有空隙的边框。

我目前的结果是这样的:

我想要实现的是灰色边框位于黄色视图之外。现在他们画的是灰线中间还是黄色的。

我试过戴面具,但只剪掉了当然的外侧。

我的代码:

struct Config {
    let start: CGFloat
    let end: CGFloat
    let color: UIColor
}

extension UIView {
    func drawBorders(for configs: [Config], lineWidth: CGFloat = 3.5) {
        let circlePath = UIBezierPath(arcCenter: CGPoint (x: self.bounds.size.width / 2,
                                                          y: self.bounds.size.height / 2),
                                      radius: self.bounds.size.width / 2,
                                      startAngle: CGFloat(-0.5 * Double.pi),
                                      endAngle: CGFloat(1.5 * Double.pi),
                                      clockwise: true)

        for config in configs {
            let circleShape = CAShapeLayer()
            circleShape.path = circlePath.cgPath
            circleShape.strokeColor = config.color.cgColor
            circleShape.fillColor = UIColor.clear.cgColor
            circleShape.lineWidth = lineWidth
            circleShape.strokeStart = config.start
            circleShape.strokeEnd = config.end

            self.layer.addSublayer(circleShape)

//            let maskLayer = CAShapeLayer()
//                 maskLayer.frame = self.bounds
//            maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: self.bounds.size.width / 2, height: self.bounds.size.width / 2)).cgPath
//                 self.layer.mask = maskLayer
        }
    }
}

还在评论中添加了掩码代码以显示我的尝试。

测试代码:

    let roundView = UIView(frame: CGRect(x: 100, y: 100, width: 150, height: 150))
    roundView.backgroundColor = .yellow
    roundView.layer.cornerRadius = roundView.frame.size.width / 2

    let config1 = Config(start: 0.125, end: 0.25, color: .gray)
    let config2 = Config(start: 0.375, end: 0.5, color: .gray)
    let config3 = Config(start: 0.625, end: 0.75, color: .gray)
    let config4 = Config(start: 0.875, end: 1, color: .gray)

    roundView.drawBorders(for: [config1, config2, config3, config4])
    view.addSubview(roundView)

有人可以帮帮我吗?

更改您的 circlePath .... 在 radius 中包含 linewidth 将解决您的问题

let circlePath = UIBezierPath(arcCenter: CGPoint (x: self.bounds.size.width / 2,
                                                          y: self.bounds.size.height / 2),
                                      radius: (self.bounds.size.width / 2) + lineWidth/2,
                                      startAngle: CGFloat(-0.5 * Double.pi),
                                      endAngle: CGFloat(1.5 * Double.pi),
                                      clockwise: true)