Skip to content

Instantly share code, notes, and snippets.

@robrasmussen
Created April 23, 2015 14:56
Show Gist options
  • Save robrasmussen/230711013c095e9ab9ed to your computer and use it in GitHub Desktop.
Save robrasmussen/230711013c095e9ab9ed to your computer and use it in GitHub Desktop.
Spirograph playground based on Erica Sadun's
import UIKit
import Foundation
import XCPlayground
struct SpirographGenerator : GeneratorType {
var pointOffset, dTheta, dR, minorRadius, majorRadius : Double
var theta = 0.0
typealias Element = CGPoint
init(majorRadius : Double, minorRadius : Double, pointOffset : Double, samples : Double)
{
self.pointOffset = pointOffset
self.dTheta = Double(M_PI) * (2.0) / samples
self.majorRadius = majorRadius
self.minorRadius = minorRadius
self.dR = majorRadius - minorRadius
}
mutating func next() -> CGPoint? {
var xT : Double = dR * cos(theta) + pointOffset * cos(dR * theta / minorRadius)
var yT : Double = dR * sin(theta) + pointOffset * sin (dR * theta / minorRadius)
theta = theta + dTheta
return CGPoint(x: xT, y: yT)
}
}
class SpiroView : UIView {
var gen:SpirographGenerator = SpirographGenerator(majorRadius: 100, minorRadius: 12, pointOffset: 22, samples: 500)
var points:Int = 50 {
didSet {
setNeedsDisplay()
}
}
var strokeColor:UIColor = UIColor.whiteColor()
override func drawRect(rect: CGRect) {
let midX = rect.width / 2
let midY = rect.height / 2
let ctx = UIGraphicsGetCurrentContext()
strokeColor.set()
for x in 1..<points {
if let p = gen.next() {
CGContextAddEllipseInRect(ctx, CGRect(x: p.x + midX, y: p.y + midY, width: 1, height: 1))
}
}
CGContextDrawPath(ctx, kCGPathFillStroke)
}
}
let v = SpiroView(frame: CGRect(x:0, y:0, width:250, height:250))
v.strokeColor = UIColor.redColor()
v.points = 8000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment