计算机图形学之DDA画线算法Bresenham算法程序

opengl程序,需要导入glut和glew库才能正常运行

#include <GL/glew.h>
#include <GL/glut.h>
#include <math.h>  
#include <stdlib.h>  

#pragma comment (lib, "glew32.lib")

/*程序运行之前请导入glut库和glew库*/
void init(void){
	glClearColor(1.0,1.0,1.0,0.0);  //设置窗口背景色为白色
	glMatrixMode(GL_PROJECTION);   //设置投影类型(模式)
	gluOrtho2D(0.0,200.0,0.0,150.0);//指定屏幕区域坐标范围,横向是0到200米,纵向是0到150米,

}

void lineSegment(void){
	glClear (GL_COLOR_BUFFER_BIT); //清除屏幕

	glColor3f(1.0,0.0,0.0);  //设置线条颜色为红色
	glBegin (GL_LINES);  //建立线段坐标(5,5)-(195,145)
	    glVertex2i(5,5);  
		glVertex2i(195,145); 
    glEnd();

	glFlush();  //强制刷新缓冲

}

//取整函数
int round(float a){
	return (int)(a+0.5);
}

//DDA画线
void lineDDA(void){
	int x0=100;int y0=5;int xEnd=195;int yEnd=145;
	int dx = xEnd - x0, dy = yEnd - y0, steps, k;
	float xIncrement, yIncrement, x = x0, y = y0;
	if (fabs (dx) > fabs (dy))
		steps = fabs (dx);
	else
		steps = fabs (dy);
	xIncrement = (float )(dx) / (float )(steps);
	yIncrement = (float )(dy) / (float )(steps);
	glClear (GL_COLOR_BUFFER_BIT); //清除屏幕
	glColor3f(0.0,0.0,1.0);  //设置线条颜色为蓝色
	glBegin (GL_POINTS);  //画点
		glVertex2i(round(x),round(y));
	    for (k = 0; k < steps; k++) {
			x += xIncrement;
			y += yIncrement;
			glVertex2i(round(x),round(y));
		}
    glEnd();

	glFlush();  //强制刷新缓冲

}

//Bresenham画线,要求斜率绝对值小于1
/* Bresenham line-drawing procedure for |m| < 1.0. */
void lineBresenhanms (void)
{
	int x0=2;int y0=20;int xEnd=100;int yEnd=90;
	int dx = fabs (xEnd - x0), dy = fabs(yEnd - y0);
	int p = 2 * dy - dx;
	int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
	int x, y;
	/* Determine which endpoint to use as start position. */
	if (x0 > xEnd) {
		x = xEnd;
		y = yEnd;
		xEnd = x0;
	}
	else {
		x = x0;
		y = y0;
	}
	glClear (GL_COLOR_BUFFER_BIT); //清除屏幕
	glColor3f(0.0,1.0,0.0);  //设置线条颜色为绿色
	glBegin (GL_POINTS);  //画点
		glVertex2i(x,y);
		while (x < xEnd) {
			x++;
			if (p < 0)
				p += twoDy;
			else {
				y++;
				p += twoDyMinusDx;
			}
			glVertex2i(x,y);
		}
	glEnd();

	glFlush();  //强制刷新缓冲
}
int main(int argc, char** argv)  
{  
	glutInit(&argc,argv);  //初始化GLUT
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);//设置显示模式
	glutInitWindowPosition (100,100); //设置窗口左上角坐标
	glutInitWindowSize(400,300); //设置窗口的宽高
	glutCreateWindow ("GLUT画线"); //创建窗口
	init(); //初始化
	//glutDisplayFunc(lineBresenhanms);//Bresenhanms画线
	//glutDisplayFunc(lineSegment);//用GLUT函数画线
	glutDisplayFunc(lineDDA);//DDA画线
	glutMainLoop(); //绘图主循环
}


你可能感兴趣的:(OpenGL,DDA,计算机图形学,Bresenham)