Bresenham line doesn't terminate

半世苍凉 提交于 2019-12-08 03:20:33

问题


I've implemented the Bresenham algorithm from Wikipedia in python but for some lines it doesn't work, like from 1,0 to 0,1 it doesn't stop and keeps going on to make a super long line

def line(x0, y0, x1, y1):
    dx = x1 - x0
    dy = y1 - y0
    sx = x0 < x1 and 1 or -1
    sy = y0 < y1 and 1 or -1
    err = dx - dy

    points = []
    x, y = x0, y0
    while True:
        points += [(x, y)]
        if x == x1 and y == y1:
            break
        e2 = err * 2
        if e2 > -dy:
            err -= dy
            x += sx
        if e2 < dx:
            err += dx
            y += sy
    return points

回答1:


You are missing the call to abs in the initialization of dx and dy:

dx = abs(x1 - x0)
dy = abs(y1 - y0)



回答2:


You have a type in "if e2 > -dy:". The minus sign is wrong.



来源:https://stackoverflow.com/questions/7159228/bresenham-line-doesnt-terminate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!