Skip to content

Instantly share code, notes, and snippets.

@phynet
Forked from jaylyerly/Golden
Created May 24, 2017 15:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phynet/3e1b1292e79aa63f7046b99ecc34970e to your computer and use it in GitHub Desktop.
Save phynet/3e1b1292e79aa63f7046b99ecc34970e to your computer and use it in GitHub Desktop.
Draw the Golden Spiral in Swift
let 𝜋 = M_PI
let ɸ = (1 + sqrt(5))/2
func drawTiles(tileCount: Int, height: Double, context: CGContext) {
let red = CGFloat(arc4random_uniform(100)) / 100.0
let green = CGFloat(arc4random_uniform(100)) / 100.0
let blue = CGFloat(arc4random_uniform(100)) / 100.0
context.setFillColor(red: red, green: green, blue: blue, alpha: 1.0)
let rect = CGRect(x: 0, y: 0, width: height, height: height) // CGFloat, Double, Int
context.fill(rect)
let arc = UIBezierPath();
let center = CGPoint(x: height, y: height)
arc.addArc(withCenter: center,
radius: CGFloat(height),
startAngle: -(CGFloat)(𝜋),
endAngle: CGFloat(-𝜋/2),
clockwise: true)
arc.stroke()
let scale = 1 / ɸ
if (tileCount > 0){
context.rotate(by: CGFloat(𝜋/2))
context.translateBy (x: 0 , y: -CGFloat(height) * CGFloat((1+scale)));
context.scaleBy(x: CGFloat(scale), y: CGFloat(scale))
drawTiles( tileCount: (tileCount-1), height: height, context: context)
}
}
func drawGoldenSpiral(tileCount: Int, height: Double) -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: height * ɸ, height: height))
drawTiles(tileCount: tileCount, height: height, context: UIGraphicsGetCurrentContext()!)
let spiralImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return spiralImage!
}
let spiralImage = drawGoldenSpiral(tileCount: 12, height: 1000.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment