基本上我想创建一个计时器应用程序。这就是为什么我需要一个圈来显示计时器的进度。如果计时器持续10秒钟,则圆圈将分为10段,每段将在1秒钟后出现。好的。

我已经从SO post -> draw-a-circular-segment-progress-in-swift成功创建了它,但是有点问题。我圈子的细分是从第四象限开始的,但是这并不是预期的。我想显示第一象限中的分段。在这里,我为8个细分创建了此函数。

请提供可以动态使用的建议。

 func createCircle(){

        let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.size.width/2,y: view.frame.size.height/2), radius: CGFloat(90), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)


        let segmentAngle: CGFloat = (360 * 0.125) / 360

        for i in 0 ..< 8 {

            let circleLayer = CAShapeLayer()
            circleLayer.path = circlePath.CGPath

            // start angle is number of segments * the segment angle
            circleLayer.strokeStart = segmentAngle * CGFloat(i) //I think all is for this line of code.

            print("\nStroke \(i): ",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)

        }

        for i in 0 ..< 8{
            view.layer.addSublayer(segments[i])
        }
    }

最佳答案

您必须偏移起始角度:

circleLayer.strokeStart = segmentAngle * CGFloat(i) - M_PI / 2.0

虽然转换也可以解决问题,但在这种情况下,我不建议使用一个转换。如果以后由于其他原因(动画等)想要进行转换,则可能还必须考虑当前的任何转换,这可能会使事情变得更复杂。

编辑:

我认为您的其他一些代码也可能会关闭。我没有弄清楚发生了什么,而是继续进行了重新编写(使用Swift 3语法):
let count: Int = 8
let gapSize: CGFloat = 0.008
let segmentAngleSize: CGFloat = (2.0 * CGFloat(M_PI) - CGFloat(count) * gapSize) / CGFloat(count)
let center = CGPoint(x: view.frame.size.width / 2.0, y: view.frame.size.height / 2.0)
let radius: CGFloat = 90
let lineWidth: CGFloat = 10
let strokeColor = UIColor(red:0,  green:0.004,  blue:0.549, alpha:1).cgColor

for i in 0 ..< count {
    let start = CGFloat(i) * (segmentAngleSize + gapSize) - CGFloat(M_PI / 2.0)
    let end = start + segmentAngleSize
    let segmentPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)

    let arcLayer = CAShapeLayer()
    arcLayer.path = segmentPath.cgPath
    arcLayer.fillColor = UIColor.clear.cgColor
    arcLayer.strokeColor = strokeColor
    arcLayer.lineWidth = lineWidth

    self.view.layer.addSublayer(arcLayer)
}

ios - 如何快速从第一象限分割圆-LMLPHP

10-08 16:56