Skip to content

Instantly share code, notes, and snippets.

@chris-hatton
Last active September 20, 2016 15:52
Show Gist options
  • Save chris-hatton/2b73c367ff4746c40f4174634e1d5420 to your computer and use it in GitHub Desktop.
Save chris-hatton/2b73c367ff4746c40f4174634e1d5420 to your computer and use it in GitHub Desktop.
Weekend Playground fun: TreeView
import UIKit
typealias Bough = (rotation:CGFloat, length: CGFloat, scale: CGFloat, hue: CGFloat)
final class TreeView : UIView {
private let limit = 10
private let boughs : [Bough] = [
(rotation: -25, length: 85, scale: 0.75, hue: 0.04),
(rotation: 30, length: 100, scale: 0.65, hue: 0.02)
]
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
context.setLineCap(.round)
context.setLineWidth(24)
context.translateBy(x: self.center.x, y: self.frame.size.height - 25)
context.move(to: CGPoint.zero)
context.rotate(by: CGFloat.pi )
branch( context: context, hue: 0.05, depth: 0 )
}
func branch( context: CGContext, hue: CGFloat, depth: Int ) {
guard depth < limit else { return }
for bough in boughs {
context.saveGState(); defer { context.restoreGState() }
let point = CGPoint(x:0,y:bough.length)
context.rotate(by: bough.rotation * CGFloat.pi / 180 )
context.setStrokeColor( UIColor(hue: hue, saturation: 0.8, brightness: 0.6, alpha: 1.0 ).cgColor )
context.move(to: CGPoint.zero)
context.addLine(to: point)
context.strokePath()
context.translateBy(x: 0, y: bough.length)
context.scaleBy(x: bough.scale, y: bough.scale)
self.branch(context: context, hue: (hue + bough.hue), depth: depth + 1)
}
}
}
let view = TreeView(frame: CGRect(x: 0, y: 0, width: 512, height: 384))
@chris-hatton
Copy link
Author

chris-hatton commented Sep 17, 2016

screen shot 2016-09-17 at 10 39 33 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment