Skip to content

Instantly share code, notes, and snippets.

@eparadis
Created January 25, 2015 23:02
Show Gist options
  • Save eparadis/5a7838f4fb629f03593b to your computer and use it in GitHub Desktop.
Save eparadis/5a7838f4fb629f03593b to your computer and use it in GitHub Desktop.
draw a fractal tree in Pythonista for iOS
import canvas
import math
branches_drawn = 0
def along( start, direction, fraction):
'''return a start point fraction amount in direction'''
newstart = ( start[0] + fraction * direction[0] * math.sin(direction[1]),
start[1] + fraction * direction[0] * math.cos(direction[1]) )
return newstart
def find_branches( start, direction):
'''return a list of pairs of start+direction values for branches of the given start+direction pair'''
# the branch parameters. these must all at least as long as angles!
angles = [ 90, -90 ]
start_fraction = [ .5, .5, 1, 1]
lengths = [ .67, .67, .67, 0 ]
result = []
for i in range(0, len( angles)):
result.append( ( along( start, direction, start_fraction[i]),
( direction[0]*lengths[i], direction[1]+math.radians(angles[i]) )
)
)
return result
def draw_branch( start, direction):
length = direction[0]
#canvas.set_stroke_color( 0, color_map(length), 0)
#canvas.set_line_width( (1 - color_map(length)) * 3 )
endpoint = along( start, direction, 1.0)
canvas.draw_line(start[0], start[1], endpoint[0], endpoint[1] )
global branches_drawn
branches_drawn += 1
if branches_drawn % 10000 == 0:
canvas.end_updates()
canvas.begin_updates()
def draw_tree( start, direction):
draw_branch( start, direction)
branches = find_branches( start, direction)
for branch in branches:
draw_branch( branch[0], branch[1])
if branch[1][0] > 5:
draw_tree( branch[0], branch[1])
def color_map(value):
'''return a value between 0..1 with an intersting map for colors'''
max = 128 # max possible length of a branch
min = 5 # min possible length of a branch
normalized = (value - min) / max
reverse_norm = 1 - normalized
return math.pow( reverse_norm, 3)
w = 1000
h = 800
canvas.set_size(w, h)
start = ( w / 2, 10)
direction = ( 600, 0 ) # length, angle in radians with 0 being 'up'
canvas.begin_updates()
draw_tree( start, direction )
canvas.end_updates()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment