一 DDA算法
(一) 原理:DDA算法跟在坐标系中画直线类似
x | 1 | 2 | 3 | 4 | 5 | 6 |
y | 1.5 | 2 | 2.5 | 3 | 3.5 | 4 |
在坐标系中描绘这六个点,用线连接起来,就是函数的直线
DDA算法简单来说寻找合适的进度(例如,x方向,从起点x=1到x=6,x_length=5),求得其步长(x_step=(6-1)/x_length=1,y_step=(4-1)/x_length=0.6),从起点到终点求得所有值
x | x1=1 | x2=x1+x_step=1+1=1 | x3=x2+x_step=2+1=3 | x4=x3+x_step=3+1=1 | x5=x4+x_step=4+1=5 | x6=x5+x_step=5+1=6 |
y | y1=1 | y2=y1+y_step=1+0.6=1.6 | y2=y1+y_step=1.6+0.6=2.2 | y2=y1+y_step=2.2+0.6=2.8 | y2=y1+y_step=2.8+0.6=3.4 | y2=y1+y_step=3.4+0.6=4 |
y取整 | 1 | 2 | 2 | 3 | 3 | 4 |
openGL画图
注释:真实的像素点是很小的,为了方便表示,我用一个格式表示一个像素点,如右边的图所示
(二)直线实现DDA算法(引用于https://blog.csdn.net/u010900851/article/details/9047133)
1、已知直线的两端点坐标:(x1,y1),(x2,y2)
2、已知画线的颜色:color
3、计算两个方向的变化量:dx=x2-x1
dy=y2-y1
4、求出两个方向最大变化量的绝对值:
steps=max(|dx|,|dy|)
5、计算两个方向的增量(考虑了生成方向):
xin=dx/steps
yin=dy/steps
6、设置初始象素坐标:x=x1,y=y1
7、用循环实现直线的绘制:
for(i=1;i<=steps;i++)
{ putpixel(x,y,color);/*在(x,y)处,以color色画点*/
x=x+xin;
y=y+yin;
}
(三)代码表示
#include <math.h>
void DDALine(int x1, int y1, int x2, int y2, int color)
{
float increx,increy,x,y;
int steps,i;
if(abs(x2-x1)>abs(y2-y1))
steps= abs(x2-x1);
else
steps= abs(y2-y1);
increx=(float)(x2-x1)/steps;
increy=(float)(y2-y1)/steps;
x=x1;
y=y1;
for(i=1;i<=steps;i++)
{
putpixel(x,y,color); //在(x,y)处,以color色画点
x+=increx;
y+=increy;
}
}
(四)完整代码
我挂在了GitHub上了,自行下载点击打开链接