修改Bresenham线算法

2 投票
1 回答
3387 浏览
提问于 2025-04-15 22:08

我正在尝试使用布雷森汉姆线算法来计算网格上的视野。我的代码可以顺利计算出线条,但我遇到的问题是,无法确保每条线都从起点到终点。为了让所有返回的线条都从 (x0,y0) 到 (x1,y1),我需要做些什么呢?

def bresenham_line(self, x0, y0, x1, y1):
    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0  
        x1, y1 = y1, x1

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

    if y0 < y1: 
        ystep = 1
    else:
        ystep = -1
        
    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = -deltax / 2
    y = y0

    line = []    
    for x in range(x0, x1 + 1):
        if steep:
            line.append((y,x))
        else:
            line.append((x,y))
                
        error = error + deltay
        if error > 0:
            y = y + ystep
            error = error - deltax
    return line

1 个回答

4

记得你是否交换了x0和x1,如果交换了,就把列表反转一下。

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

变成

switched = False
if x0 > x1:
    switched = True
    x0, x1 = x1, x0
    y0, y1 = y1, y0

最后,只需添加:

if switched:
    line.reverse()

撰写回答