2012-03-12 19:33:35|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 图形/图像, MFC|来源:唯设编程网
// 执行绘图操作 void COpenGLLib::draw(){ //启用双缓存 static BOOL bBusy=FALSE; if(bBusy) return; bBusy=TRUE; //背景色 glClearColor(0.2f,0.2f,0.5f,1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //棋盘位图 double bitmap[100]={ 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,1, 0,0,0,0,0,1,0,0,0,1 }; CMatrix matrixBitmap(10,10,bitmap); //绘制棋盘 drawChessboard(matrixBitmap); //完成绘制 glFinish(); //双缓存应用 SwapBuffers(wglGetCurrentDC()); bBusy=FALSE; }
为了避免屏幕闪烁,本示例中使用了双缓存技术,为了增加程序的通用性和扩展性,本示例将具体的绘制逻辑独立出来了,具体的绘制代码如下:
//draw的实现函数,以后采用外部接入的方式 void COpenGLLib::drawChessboard(CMatrix& bitmap){ //移动 glTranslatef(-0.0f,0.0f,-6.0f); glScalef(1.0f,1.0f,1.0f); //glRotatef(90.0f,1.0f,0.0f,0.0f); //1.画棋盘 glLineWidth(lWidth[1]); //设置线宽 //接受线型设置 glEnable(GL_LINE_STIPPLE); glEnable(GL_POINT_SMOOTH); //设置线型 glLineStipple(1,0xFFFF); glBegin(GL_LINES); glColor3f(0.0f,1.0f,1.0f); //画竖线 for(GLfloat i=0;i<bitmap.getRowCount();i++){ glVertex3f(i-4.5f,-4.5f,0.0f); glVertex3f(i-4.5f,4.5f,0.0f); } //画横线 for(GLfloat j=0;j<bitmap.getColCount();j++){ glVertex3f(-4.5f,j-4.5f,0.0f); glVertex3f(4.5f,j-4.5f,0.0f); } glEnd(); glDisable(GL_POINT_SMOOTH); glDisable(GL_LINE_STIPPLE); //2.画棋子 for(size_t row=1;row<=bitmap.getRowCount();row++){ for(size_t col=1;col<=bitmap.getColCount();col++){ if(fabs(bitmap[row][col]-1.0)<1e-10){ glPushMatrix(); glTranslatef((GLfloat)col-1.0f-4.5f,-((GLfloat)row-1.0f-4.5f),0.0f); glScalef(0.5f,0.5f,1.0f); //绘制棋子 drawChessman(); glPopMatrix(); } } } } //绘制一个棋子 //直径为1 void COpenGLLib::drawChessman(){ GLfloat radius=0.5f; //半径 //1.画基座圆 glBegin(GL_TRIANGLE_FAN); glColor3f(1.0f,0.0f,1.0f); glVertex3f(0.0f,0.0f,0.0f); glColor3f(0.0f,1.0f,0.0f); for(GLfloat angle=0;angle<361;angle++){ glVertex3f(radius*cos(PI*angle/180.0f),radius*sin(PI*angle/180.0f),0.0f); } glEnd(); //2.画上部拱形 glBegin(GL_QUAD_STRIP); glColor3f(0.5f,0.0f,1.0f); for(GLfloat angle=0;angle<182;angle++){ glPushMatrix(); glRotatef(angle,0.0f,0.0f,1.0f); //绕Z轴旋转对应角度° for(GLfloat x=-0.5;x<=0.5;x+=0.05f){ glPushMatrix(); glVertex3d(x,0.0,-1.2*x*x+0.2); glRotatef(1.0f,0.0f,0.0f,1.0f); //绕Z轴旋转1° glVertex3d(x,0.0,-1.2*x*x+0.2); glPopMatrix(); } glPopMatrix(); } glEnd(); }
至此,OpenGL绘图类COpenGLLib就已经完成了,本类主要演示了OpenGL环境的配置方法,供入门的初学者参考,所以仅仅绘制了一个简单的五子棋棋盘。下面我们将编写COpenGLLib的测试程序。