//DDA算法 void DDALine(int x0, int y0, int x1, int y1) { int dx,dy,eps,k; float x,y,xIncre,yIncre; dx=x1-x0; dy=y1-y0; x=x0; /*开始每次运行都不出结果,仔细检查了好几遍DDALine都没看出问题,最后才发现x和y没有赋初值*/ y=y0; //判断K的绝对值是大于1还是大于0 小于1 //esp=(abs(dx)<abs(dy)) ? abs(dx) : abs(dy); if(abs(dx)>abs(dy)) eps=abs(dx); else eps=abs(dy); //x和y每一步都增量 xIncre=(float)dx/(float)eps; yIncre=(float)dy/(float)eps;
glClear(GL_COLOR_BUFFER_BIT); //设置描点的大小 glPointSize(2.0f); //开始画图 glBegin(GL_POINTS); glColor3f(1.0f,0.0f,0.0f); glVertex2i((int)(x+0.5),(int)(y+0.5)); glEnd(); glFlush();
for(k=0;k<=eps;k++) { glBegin(GL_POINTS); glColor3f(1.0f,0.0f,0.0f); glVertex2i((int)(x+0.5),(int)(y+0.5)); glEnd();
x+=xIncre; y+=yIncre;
glFlush(); } }
//中点Bresenham算法 void MidBresenhamLine(int x0, int y0, int x1, int y1) { //设置直线颜色 glColor3f(0.0f,1.0f,0.0f); //设置描点大小 glPointSize(3.0f);
int dx,dy,d,UpIncre,DownIncre,x,y; if(x0>x1) { x=x1;x1=x0;x0=x; y=y1;y1=y0;y0=y; } x=x0;y=y0; dx=abs(x1-x0); dy=abs(y1-y0); d=dx-2*dy;
glBegin(GL_POINTS); glVertex2i(x,y); glEnd(); glFlush();
UpIncre=2*dx-2*dy; DownIncre=-2*dy;
while(x<=x1) { if(d<0) { x++; y++; d+=UpIncre; } else d+=DownIncre;
glBegin(GL_POINTS); glVertex2i(x,y); glEnd(); glFlush(); }
}
//改进的Bresenhamline算法 void BresenhamLine(int x0, int y0, int x1, int y1) { glColor3f(0.0f,0.0f,1.0f); glPointSize(3.0f);
int x,y,dx,dy,e; dx=x1-x0; dy=y1-y0; e=-dx; x=x0; y=y0;
glBegin(GL_POINTS); glVertex2i(x,y); glEnd(); glFlush();
while(x<=x1) { glBegin(GL_POINTS); glVertex2i(x,y); glEnd(); glFlush(); x++; e=e+2*dy; if(e>0) { y++; e=e-2*dx; } } }
//回调函数 void onDisplay() { int x0=0,y0=0; int x1=200,y1=200; DDALine(x0,y0,x1,y1); MidBresenhamLine(x0+10,y0,x1+10,y1); BresenhamLine(x0+20,y0,x1+20,y1); }
void onReshape(int w, int h) { glClearColor(1.0f,1.0f,1.0f,0.0f); // 设置背景颜色(白色) gluOrtho2D(0,w,0,h); }
int main(int argc, char* argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE); glutInitWindowSize(500,500); glutCreateWindow("画直线算法"); glutDisplayFunc(&onDisplay); glutReshapeFunc(onReshape);
glutMainLoop(); return 0; }