具有相同扇区的多种颜色的 UIView 边框

UIView border with several colors with equal sectors

例如,我有一个 UIView,我需要用 3 种颜色制作边框。 我可以这样做:

func addDividedColors(colors:[UIColor], width:CGFloat = 1) {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame =  CGRect(origin: .zero, size: self.bounds.size)
    var colorsArray: [CGColor] = []
    var locationsArray: [NSNumber] = []
    for (index, color) in colors.enumerated() {
        colorsArray.append(color.cgColor)
        colorsArray.append(color.cgColor)
        locationsArray.append(NSNumber(value: 1.0 / Double(colors.count) * Double(index)))
        locationsArray.append(NSNumber(value: 1.0 / Double(colors.count) * Double(index + 1)))
    }

    gradientLayer.locations = locationsArray
    gradientLayer.colors = colorsArray

    let shape = CAShapeLayer()
    shape.lineWidth = width
    shape.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: width/2, dy: width/2), cornerRadius: self.cornerRadius).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradientLayer.mask = shape
    self.insertSublayer(gradientLayer, at: 0)
}

但我会看到有 4 个扇区的边框:

但它应该看起来像:

唯一的方法是用多种颜色创建圆圈,还是可以通过边框来实现? 谢谢!

所以,我终于完成了这个任务。这是 CALayer 的扩展:

func addDividedColors(colors: [UIColor], width: CGFloat = 10) {
        let circlePath = UIBezierPath(ovalIn: frame)
        var segments: [CAShapeLayer] = []
        let segmentAngle: CGFloat = 1.0/CGFloat(colors.count)
        for index in 0..<colors.count{
            let circleLayer = CAShapeLayer()
            circleLayer.path = circlePath.cgPath

            // start angle is number of segments * the segment angle
            circleLayer.strokeStart = segmentAngle * CGFloat(index)

            // end angle is the start plus one segment
            circleLayer.strokeEnd = circleLayer.strokeStart + segmentAngle

            circleLayer.lineWidth = width
            circleLayer.strokeColor = colors[index].cgColor
            circleLayer.fillColor = UIColor.clear.cgColor

            // add the segment to the segments array and to the view
            segments.insert(circleLayer, at: index)
            addSublayer(segments[index])
        }
    }

以及现在的样子: