只給出繪制圖形的代碼,別的代碼前面的文章有,可以參照。
繪制金字塔的函數:
void GLWidget::paintGL()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
//renderText(10,20,"Hello,My Dear");
// glColor3f(1.0, 0.0, 0.0);
/*
glBegin(GL_TRIANGLES);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(-1.0, -1.0, 0.0);
glVertex3f(1.0, -1.0, 0.0);
glEnd();
*/
// glTranslatef(-1.5, 0.0, -6.0);
// glRotatef(rTri, 0.0, 0.0, 1.0);
/*************************三角形************************
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glEnd();
*****************************************************/
glRotatef(rTri, 0.0f, 1.0f, 0.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
glLoadIdentity();
renderText(20, 100, "Hello Jcy, OpenGL welcome to you.");
}
在編寫這種三維圖形的時候需要注意的一個問題就是模式的選擇,開始的時候我選擇的是GL_FLAT模式,這種模式畫出來的效果就是前面介紹三角形繪制時候的效果,全部是藍色,但是我的三角形代碼跟這個上面的代碼是一樣的,而我現在選擇的是GL_SMOOTH模式,這種方式出來的效果就是下面的效果,顯而易見的,GL_SMOOTH畫出來的更能展現出三維,更立體。
具體關於這兩種模式的區別,大家可以參考:http://www.linuxidc.com/Linux/2012-12/76070.htm
效果如下:
旋轉時候的效果: