OpenGL画点、直线、虚线和多边形

时间:2021-10-23 09:24:40

// 从这里开始进行所有的绘制

int DrawGLScene(GLvoid)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清除屏幕和深度缓存
glLoadIdentity();// 重置当前的模型观察矩阵
glColor3f(1.0, 0.0,0.0); //设置接下来所要画的东西的颜色
//绘制一个矩形,默认为填充模式
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON);// 设置各个顶点,glBegin开始,glEnd结束
	glVertex3f(0.25,0.25,0.4);
	glVertex3f(0.75,0.25,0.4);
	glVertex3f(0.75,0.75,0.4);
	glVertex3f(0.25,0.75,0.4);
glEnd(); 

glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glPointSize(10);//画点,通过glPointSize设置一个点的宽度
glBegin(GL_POINTS);
	glVertex3f(0.25,0.25,0.0);
	glVertex3f(0.75,0.25,0.0);
	glVertex3f(0.75,0.75,0.0);
	glVertex3f(0.25,0.75,0.0);
glEnd();

glPointSize(1);//画 虚线 ,点线,通过glLineStipple设置虚线模型,然后enable GL_LINE_STIPPLE开关
glLineStipple(2, 0x5555);
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINES);
        glVertex3f(0.25,0.85,0.6);
        glVertex3f(0.75,0.85,0.6);
glEnd();

glDisable(GL_LINE_STIPPLE);//画圆,通过glLineWidth设置直线的宽度
glColor3f(1.0,0.0,0.0);//颜色修改为红色
glLineWidth(10);    
glBegin(GL_LINE_LOOP);
#define   PI   3.1415926f
#define   POINTS   100
float  angel = 0.0f;
for (int i =0  ; i<POINTS; i++) {
	angel = 2.0f * PI  * i / POINTS;
	glVertex3f(cos(angel),sin(angel),0.5f);
}
	glEnd();
	glLineWidth(1);
	glFlush();
	return TRUE;
}
// 以下是关于缓存的一些函数
glClearDepth(1.0f);// 设置深度缓存
glEnable(GL_DEPTH_TEST);// 启用深度测试
glDepthFunc(GL_LEQUAL);// 所作深度测试的类型

下面附上奥运五环小程序及其运行结果:

</pre><pre name="code" class="cpp">
#include <GL/glut.h>
#include <GL/GLAUX.H>


GLuint OlympicRings;


void initialize(){
	glClearColor(0.25, 0.0, 0.2, 10.5);	  //清屏,设置底部为白色
	OlympicRings = glGenLists(1);		  //显示列表


	glNewList(OlympicRings, GL_COMPILE);
		
		glColor3f(1.0, 1.0, 0.0);         //绘制黄色圆环
		glTranslatef(-25.0, -15.0, 0.0);  //坐标移动
		glutSolidTorus(1, 20.0, 15, 60);


		glColor3f(0.0, 1.0, 0.0);		  //绘制绿色圆环
		glTranslatef(45.0, 0.0, 0.0);	  //坐标移动
		glutSolidTorus(1, 20.0, 15, 60);


		glColor3f(0.0, 0.0, 0.0);		  //绘制黑色圆环
		glTranslatef(-20.0, 25.0, 0.0);   //坐标移动
		glutSolidTorus(1, 20, 15, 60);


		glColor3f(0.0, 0.0, 1.0);		  //绘制蓝色环
		glTranslatef(-45.0, 0.0, 0.0);    //坐标移动
		glutSolidTorus(1, 20, 15, 60);


		glColor3f(1.0, 0.0, 0.0);		  //绘制红色环
		glTranslatef(90, 0.0, 0.0);		  //坐标移动
		glutSolidTorus(1, 20.0, 15, 60);
	glEndList();


}


void display(){
	glClear(GL_COLOR_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();


	glCallList(OlympicRings);//调用显示列表
	glFlush();
}


int main(){
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(800, 600);
	glutInitWindowPosition(200, 50);
	glutCreateWindow("奥运五环");


	glutDisplayFunc(display);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(-70.0f, 70.0f, -70.0f, 70.0f);
	initialize();
	glutMainLoop();
	return 0;
}
OpenGL画点、直线、虚线和多边形