Bresenhams Line algorithim
unknown
python
2 years ago
824 B
9
Indexable
import matplotlib.pyplot as plt
def bresenham_line(x0, y0, x1, y1):
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x, y = x0, y0
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
err = dx - dy
x_coords, y_coords = [], []
while True:
x_coords.append(x)
y_coords.append(y)
if x == x1 and y == y1:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x += sx
if e2 < dx:
err += dx
y += sy
return x_coords, y_coords
# Example usage
x0, y0, x1, y1 = 0, 0, 15, 10
x_coords, y_coords = bresenham_line(x0, y0, x1, y1)
plt.plot(x_coords, y_coords, marker='o')
plt.title("Bresenham's Line Algorithm")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.grid(True)
plt.show()Editor is loading...
Leave a Comment