Swift: Spiroswiftograph

My kids and I just put together a spirograph playground. The images that follow are mostly based on their choices for major/minor radii and point offsets.

Code:

struct SpirographGenerator : Generator {
    
    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)
    }
}

Screen Shot 2014-06-23 at 6.51.33 PMScreen Shot 2014-06-23 at 6.51.27 PMScreen Shot 2014-06-23 at 6.51.39 PMScreen Shot 2014-06-23 at 6.51.20 PMScreen Shot 2014-06-23 at 6.51.45 PMScreen Shot 2014-06-23 at 6.51.14 PMScreen Shot 2014-06-23 at 6.51.07 PM

9 Comments

  • […] Swift: Spiroswiftograph – a cool example of what you can do in the Playground […]

  • Could you include how you actually draw with the struct?

    • I, too, would like to know how to proceed after inputting the bit of code to an xcode playground 🙂

      • You just draw to the new x/y coordinate pair. I drew into a UI image context — UIGraphicsBegin/End/GetImageFrom

    • I put together an explanation on how to actually draw use the generator object presented here to draw an image in an Xcode 6 Playground. You can find it here: http://alanduncan.me/2014/08/17/swift-spirograph/

  • Fascinating; but as others have mentioned, would you be kind enough to include the how you actually use the Generator object to draw the image?

  • […] ago, I implemented a playground spirograph system that, quite honestly, took forever to run. Today, I updated that project to use separate source. […]

  • Is the guide to this still available? The link is broken. Thanks.

  • […] Swift: Spiroswiftograph – a cool example of what you can do in the Playground […]