在SWIFT中绘制循环段进度

时间:2015-08-04 11:16:34

标签: xcode swift uiview draw cgcontext

我想用切片创建循环进度,其中每个切片都是弧。

我的代码基于这个答案: Draw segments from a circle or donut

但我不知道如何复制它并旋转10次。 我想按照进度变量(百分比)对其进行着色。

编辑:我想要这样的事情

enter image description here

请帮助

此致

1 个答案:

答案 0 :(得分:7)

您可以使用圆形路径并设置strokeStart和StrokeEnd。像这样:

let circlePath = UIBezierPath(ovalInRect: CGRect(x: 200, y: 200, width: 150, height: 150))
var segments: [CAShapeLayer] = []
let segmentAngle: CGFloat = (360 * 0.125) / 360

for var i = 0; i < 8; i++ {
    let circleLayer = CAShapeLayer()
    circleLayer.path = circlePath.CGPath

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

    // end angle is the start plus one segment, minus a little to make a gap
    // you'll have to play with this value to get it to look right at the size you need
    let gapSize: CGFloat = 0.008
    circleLayer.strokeEnd = circleLayer.strokeStart + segmentAngle - gapSize

    circleLayer.lineWidth = 10
    circleLayer.strokeColor = UIColor(red:0,  green:0.004,  blue:0.549, alpha:1).CGColor
    circleLayer.fillColor = UIColor.clearColor().CGColor

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