直线DDA算法实现:
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;
}
直线DDA算法特点:
该算法简单,实现容易,但由于在循环中涉及实型数的运算,因此生成直线的速度较慢。
直线DDA算法程序:
#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;
}
}
【转自】http://course.cug.edu.cn/cugfirst/computer_graphics/class/course/2-1-1-a.htm#