布雷森纳姆线没有终点站
我已经在Python中实现了来自维基百科的 Bresenham 算法,但对于某些行却没有工作,就像从 1,0 到 0,1 它不会停止并继续形成一条超长的线
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在
dx
和dy
的初始化中缺少对abs
的调用:You are missing the call to
abs
in the initialization ofdx
anddy
:您的类型为“
if e2 > -dy:
”。减号是错误的。You have a type in "
if e2 > -dy:
". The minus sign is wrong.