Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active January 22, 2020 12:57
Show Gist options
  • Save scotteg/2c4b7b17344c50f47a33 to your computer and use it in GitHub Desktop.
Save scotteg/2c4b7b17344c50f47a33 to your computer and use it in GitHub Desktop.
Returns an array of `CGPoint`s that are evenly distributed around the circumference of a circle for a given radius, center x, center y, and number of decimal points precision.
import UIKit
/**
Returns an array of `CGPoint`s that are evenly distributed around the circumference of a circle for a number of points, center x, center y, and radius of the circle, and maximum number of decimal points precision for the x and y values.
- author: Scott Gardner
- parameter numberOfPoints: the number of points to plot; 1 or more
- parameter centerX: the center `x` of the circle
- parameter centerY: the center `y` of the circle
- parameter radius: the radius of the circle (distance from center)
- parameter precision: the maximum number of decimal places precision, 0 or higher, **defaults to 3**
- returns: `[CGPoint]`
*/
public func pointsOnCircleFor(numberOfPoints: UInt, centerX: CGFloat, centerY: CGFloat, radius: CGFloat, precision: UInt = 3) -> [CGPoint] {
var points = [CGPoint]()
let angle = CGFloat(M_PI) / CGFloat(numberOfPoints) * 2.0
let p = CGFloat(pow(10.0, Double(precision)))
for i in 0..<numberOfPoints {
let x = centerX - radius * cos(angle * CGFloat(i))
let roundedX = Double(round(p * x)) / Double(p)
let y = centerY - radius * sin(angle * CGFloat(i))
let roundedY = Double(round(p * y)) / Double(p)
points.append(CGPoint(x: roundedX, y: roundedY))
}
print(points)
return points
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment