Aaron Janse Aaron Janse - 4 months ago 5x
Swift Question

What unit does Swift use for angles?

Am am writing some code to draw circular charts, and while reading some example code, became confused about how angles are measured in Swift.

In the first post I read, Swift seems to use radians:

CGContextAddArc(context, origo.x, origo.y, radius, floatPi * 3 / 2, floatPi * 3 / 2 + floatPi * 2 * percent, 0)

In the second post, Swift seems to define angles as a range from 0 to 1:

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)

So, how does Swift measure angles?



Swift has absolutely nothing to do with the angle unit, it's just a Float/Double to it. It's the functions of the Core Graphics framework that specify what angle unit they're expecting. Just read the docs of the functions in question.

From the CGContextAddArc docs:

startAngle: The angle to the starting point of the arc, measured in radians from the positive x-axis.

endAngle: The angle to the end point of the arc, measured in radians from the positive x-axis.

Also the strokeStart and strokeEnd properties of the CAShapeLayer say what part of the given path should be drawn, it's not an angle. Just read the docs next time.