如何用中点Bresenham算法完成直线扫描转换?
发布网友
发布时间:2022-05-24 21:00
我来回答
共1个回答
热心网友
时间:2023-11-01 23:10
#include <gl/glut.h>
#include<math.h>
#include<stdio.h>
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<k<=1中点Bresenham算法的代码
{
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;
}