Created
June 7, 2014 23:56
-
-
Save jaylyerly/2a8f0e34e121c5d01a38 to your computer and use it in GitHub Desktop.
Draw the Golden Spiral in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground - noun: a place where people can play | |
import UIKit | |
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 | |
CGContextSetRGBFillColor(context, red, green, blue, 1.0) | |
CGContextFillRect(context, CGRectMake(0, 0, height, height)) | |
let arc = UIBezierPath(); | |
let center = CGPointMake(height, height) | |
arc.addArcWithCenter(center, | |
radius: height, | |
startAngle: -𝜋, | |
endAngle: -𝜋/2 , | |
clockwise: true) | |
arc.stroke() | |
let scale = 1 / ɸ | |
if (tileCount > 0){ | |
CGContextRotateCTM(context, 𝜋/2 ) | |
CGContextTranslateCTM (context, 0 , -height*(1+scale)); | |
CGContextScaleCTM(context, scale, scale) | |
drawTiles( (tileCount-1), height, context) | |
} | |
} | |
func drawGoldenSpiral(tileCount: Int, height: Double) -> UIImage { | |
UIGraphicsBeginImageContext(CGSize(width: height * ɸ, height: height)) | |
drawTiles(tileCount, height, UIGraphicsGetCurrentContext()) | |
let spiralImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return spiralImage | |
} | |
let spiralImage = drawGoldenSpiral(12, 500.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment