tloz1506996
tloz1506996

Reputation: 31

drawing a circle using bezier path swift

I am trying to draw a circle, which is in my custom table view cell class, based on dates. E.g. I have two date objects; date1 and date2 respectively. The closer date1 becomes closer to date2, the circle should become more completed towards being a full circle. When the amount of days is 0, there should be a full circle etc.

This is what I have at the moment:

let startAngle = CGFloat(-Double.pi/2)
    let endAngle = CGFloat(-Double.pi/2 + Double.pi * Double(2) * Double(components.day!) * 0.1)

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 80,y: 80), radius: CGFloat(60), startAngle:startAngle , endAngle:endAngle, clockwise: true)

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

    var colour = UIColor.green.cgColor

    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayer.strokeColor = colour
    //you can change the line width
    shapeLayer.lineWidth = 10.0

    cell.progressView.layer.addSublayer(shapeLayer)

The components.day! is the amount of days between the 2 dates. But the circle that gets drawn does not correlate to the the amount of days. I'm guessing I've got my angles wrong but not sure why

Upvotes: 1

Views: 2494

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You have the requirement that if the date difference (components.day) is 20 or more, the circle should be empty. If the difference is 0 then the circle should be complete. So the first thing you need to do is to compute the percentage full based on components.day.

let percentFull = 1 - Double(min(components.day!, 20)) / 20

Then you can calculate the angles:

let startAngle = CGFloat(-Double.pi / 2) // top of circle
let endAngle = startAngle + 2 * Double.pi * percentFull

let circlePath = UIBezierPath(arcCenter: CGPoint(x: 80, y: 80), radius: 60, startAngle: startAngle, endAngle: endAngle, clockwise: true)

Upvotes: 2

Related Questions