Search code examples
iosswiftuibezierpath

How to make circle based on percentage?


I can create a circle, but instead I need it to start at "12:00" and go to a certain percentage.

 let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

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

    //change the fill color
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    //you can change the line width
    shapeLayer.lineWidth = 3.0

    cell.progress.layer.addSublayer(shapeLayer)

Solution

  • You need to adjust the start and end angles to meet your criteria.

    "12:00" on the circle would be 3pi/2 or -pi/2 (- CGFloat.pi / 2). A full circle is 2pi (2 * CGFloat.pi). A percentage of that is of course CGFloat.pi * 2 * percentage. So the end would be your start + that percentage.

    let circlePath = UIBezierPath(
       arcCenter: CGPoint(x: 100, y: 100),
       radius: 20,
       startAngle: - .pi / 2,
       endAngle: - .pi / 2 + .pi * 2 * percentage ,
       clockwise: true
    )
    

    where percentage is some CGFloat in the range 0.0 to 1.0.