UIView边界有几种颜色,扇区相等

问题描述 投票:1回答:1

例如,我有一个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个部门的边界:

Output

但它应该看起来像:

Expectation

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

ios swift uikit calayer
1个回答
0
投票

所以,我终于做了这个任务。这是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])
        }
    }

它现在看起来如何:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.