用中点Bresenham算法完成直线扫描转换的完整代码

2022-08-13 科技 83阅读
#include
#include
#include

void Initial(void)
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //设置窗口背景颜色为白色
glMatrixMode(GL_PROJECTION); //设置投影参数
gluOrtho2D(-10.0,10.0,-10.0,10.0);
}

void LineMidPointBre(GLint x0, GLint y0, GLint x1, GLint y1)
{
GLint dx,dy,d,UpIncre,DownIncre,x,y;
if(x0>x1)
{
x=x1; x1=x0; x0=x;
y=y0; y1=y0; y0=y;
}
x=x0;
y=y0;
dx=x1-x0;
dy=y1-y0;
if(dy>0&&dy<=dx)//0 {
d=dx-2*dy;
UpIncre=2*dx-2*dy;
DownIncre=-2*dy;
while(x<=x1)
{
glPointSize(3);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
x++;
if(d<0)
{
y++;
d+=UpIncre;
}
else d+=DownIncre;
}
}

else if((dy>(-dx))&&dy<0) //斜率-1<=k<=0的中点Bresenham算法
{ d=dx-2*dy;
UpIncre=-2*dy;
DownIncre=-2*dx-2*dy;
while(x<=x1)
{
glPointSize(3);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
x++;
if(d>0)
{
y--;
d+=DownIncre;
}
else d+=UpIncre;
} }
else if(dy<(-dx)) //斜率k<-1中点Bresenham算法
{d=-dy-2*dx;
UpIncre=2*dx+2*dy;
DownIncre=2*dx;
while(y>=y1)
{
glPointSize(3);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
y--;
if(d<0)
{
x++;
d-=UpIncre;
}
else d-=DownIncre;
} }

else //斜率k>1和k不存在时的的中点Bresenham算法
{ d=dy-2*dx;
UpIncre=2*dy-2*dx;
DownIncre=-2*dx;
while(y<=y1)
{
glPointSize(3);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
y++;
if(d<0)
{
x++;
d+=UpIncre;
}
else d+=DownIncre;
} }

}

void Display(void)
{
glClear(GL_COLOR_BUFFER_BIT); //用当前背景色填充窗口
glColor3f(1.0f, 0.0f, 0.0f); //设置当前的绘图颜色为红色
LineMidPointBre(1,1,1,-5); //调用中点Bresenham算法实现直线的扫描转换

glFlush(); //处理所有的OpenGL程序
}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //初始化窗口的显示模式
glutInitWindowSize(360,360); //设置窗口的尺寸
glutInitWindowPosition(270,270); //设置窗口的位置
glutCreateWindow("中点Bresenham算法绘制任意斜率直线"); //设置标题
glutDisplayFunc(Display); //设置当前窗口的显示回调函数
Initial(); //完成窗口初始化
glutMainLoop(); //启动主GLUT事件处理循环
return 0;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com