Skip to content

Instantly share code, notes, and snippets.

@laserbat
Created July 20, 2011 11:56
Show Gist options
  • Save laserbat/1094829 to your computer and use it in GitHub Desktop.
Save laserbat/1094829 to your computer and use it in GitHub Desktop.
def getLine(self, x1, y1, x2, y2):
"""Bresenham's line algorithm"""
points = []
issteep = abs(y2 - y1) > abs(x2 - x1)
if issteep:
x1, y1 = y1, x1
x2, y2 = y2, x2
rev = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
rev = True
deltax = x2 - x1
deltay = abs(y2 - y1)
error = int(deltax / 2)
y = y1
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
for x in range(x1, x2 + 1):
if issteep:
points.append((y, x))
else:
points.append((x, y))
error -= deltay
if error < 0:
y += ystep
error += deltax
# Reverse the list if the coordinates were reversed
if rev:
points.reverse()
return points
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment