在OpenGl中,图形都是有一些基本的图元组成的,图元是把一组定点或顶点列表解释为屏幕上绘制的某些图形,OpenGL中的最小图元就是点。在OpenGL中有10中图元,可以实现从空间中绘制的简单的点到任意变数的封闭多边形,这十种图元分别是:
绘制图形的格式如下:
glBegin("图元类型"); glVertex3f(GLfloat x, GLfloat y, GLfloat z); glVertex3f(GLfloat x, GLfloat y, GLfloat z); glVertex3f(GLfloat x, GLfloat y, GLfloat z); ...... glEnd();下面以一个实例来说明点的绘制,该实例运用三角形的原理绘制一系列简单的点,这些点沿着Z轴上升,形成一个螺旋状的形状。整个实例的源代码如下:
#include "stdafx.h" #include <gl/glut.h> #include <cmath> #include <iostream> using namespace std; #ifndef GL_PI #define GL_PI 3.14159 #endif GLfloat xRot = 45.0f; GLfloat yRot = 30.0f; void SetupRC_GRAPHIC(void) { // black background glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set drawing color to Green glColor3f(1.0f, 1.0f, 0.0f); } // Called to draw scene void RenderScene_GRAPHIC(void) { GLfloat X, Y, Z, angle; GLfloat fR = 50.0f; // Clear the window with current color glClear(GL_COLOR_BUFFER_BIT); // Save matrix state and do the rotation glPushMatrix(); // Rotate glRotatef(xRot, 1.0f, 0.0f, 0.0f); glRotatef(yRot, 0.0f, 1.0f, 0.0f); glBegin(GL_POINTS); Z = -fR; for ( angle = 0.0f; angle<=2.0f*GL_PI*5.0f; angle+=0.1f) // 5圈 { X = fR * sin(angle); Y = fR * cos(angle); glVertex3f(X, Y, Z); Z += 0.5; } glEnd(); // restore transformations glPopMatrix(); // Flush drawing commands glFlush(); } // called by GLUT library when the window has changed size void ChangeSize_GRAPHIC(GLsizei w, GLsizei h) { GLfloat nRange = 100.0f; if ( h ==0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Reset coordinate system glMatrixMode(GL_PROJECTION); glLoadIdentity(); if ( w<= h) glOrtho(-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange); else glOrtho(-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int _tmain(int argc, char* argv[]) { glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutCreateWindow("Graphics"); glutDisplayFunc(RenderScene_GRAPHIC); glutReshapeFunc(ChangeSize_GRAPHIC); SetupRC_GRAPHIC(); glutMainLoop(); return 0; }上面代码中首先采用glOrtho()函数来建立修剪空间,当窗口发生变化时,ChangeSize()函数就会对视见区做一些调整。而在渲染函数RenderScene_GRAPHIC()中,通过计算某个角度的X、Y值(在0~PI之间循环了5次),并采用glVertex3f进行绘制,最终效果如图所示:
作者:kezunhai出处:http://blog.csdn.net/kezunhai欢迎转载或分享,但请务必声明文章出处。
学习OpenGL(三)绘制螺旋状图形,布布扣,bubuko.com
原文地址:http://blog.csdn.net/kezunhai/article/details/38535731