算法原理
DDA算法是计算机图形学中最简单的绘制直线算法。其主要思想是由直线公式y = kx + b推导出来的。
我们已知直线段两个端点P0(x0,y0)和P1(x1,y1),就能求出 k 和 b 。
在k,b均求出的条件下,只要知道一个x值,我们就能计算出一个y值。如果x的步进为1(x每次加1,即x = x +1),那么y的步进就为k+b;同样知道一个y值也能计算出x值,此时y的步进为1,x的步进为(1-b)/k。根据计算出的x值和y值,向下取整,得到坐标(x’,y’),并在(x’,y’)处绘制直线段上的一点。
算法步骤
首先,计算Δ x、Δ y、k的值
dx, dy = x2 - x1, y2 - y1
k = dy/dx
x, y = x1, y1
接着,在0~Δ x的范围内,根据x每一步的前进,计算y的值,进行画点。
for i in range(0, int(abs(dx)+1)):
#需要四舍五入
plt.plot(int(round(x)), int(round(y)), 'b.', markersize = 1)
x += 1
y += float(k)
算法结果
起点(10, 20),终点(300,220)
算法源码
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def DDA(x1, y1, x2, y2):
dx, dy = x2 - x1, y2 - y1
k = dy/dx
x, y = x1, y1
#网格线
plt.grid()
#x轴y轴数值取整
plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
#绘点
for i in range(0, int(abs(dx)+1)):
#需要四舍五入
plt.plot(int(round(x)), int(round(y)), 'b.', markersize = 1)
x += 1
y += float(k)
plt.show()
def main():
x,y = 10,20
xEnd, yEnd = 300,220
if xEnd < x:
x,y, xEnd, yEnd = xEnd, yEnd, x, y
DDA(x, y, xEnd, yEnd)
if __name__ == '__main__':
main()