Skip to content

Instantly share code, notes, and snippets.

@kentliau
Forked from chris-hatton/TreeView.swift
Created September 17, 2016 17:41
Show Gist options
  • Save kentliau/ca16fe1db80cc674965de2a586c5ccb9 to your computer and use it in GitHub Desktop.
Save kentliau/ca16fe1db80cc674965de2a586c5ccb9 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment