Untitled

Bresenhams Line Algorithm
 avatar
unknown
python
2 years ago
877 B
39
Indexable
def draw_line(x0, y0, x1, y1):
    # Initialize variables
    dx = abs(x1 - x0)
    dy = abs(y1 - y0)
    slope = dy > dx

    if slope:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if x0 > x1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    # Initialize variables for Bresenham's algorithm
    dx = x1 - x0
    dy = abs(y1 - y0)
    error = dx / 2
    y_step = 1 if y0 < y1 else -1

    y = y0
    points = []

    # Iterate over the range of x values
    for x in range(x0, x1 + 1):
        coord = (y, x) if slope else (x, y)
        points.append(coord)

        error -= dy
        if error < 0:
            y += y_step
            error += dx

    return points

# Example usage
x0, y0 = 1, 1
x1, y1 = 8, 4
line_points = draw_line(x0, y0, x1, y1)

# Print the line points
for point in line_points:
    print(point)
Editor is loading...
Leave a Comment