這篇文章是來講述如何在OpenGL中選擇圖形的,我拿上次寫的三角形來實現。
在OpenGL中有專門負責旋轉的函數glRotatef(Angle, X Vector, Y Vector, Z Vector);此函數負責讓對象繞著某個軸旋轉。
Angle通常是某個變量代表對象轉過的角度;
X Vector,Y Vector, Z Vector三個參數共同決定旋轉軸的方向,(1, 0, 0)表示描述的矢量經過X軸的1個單位處並且方向向右;
當然你還得添加鼠標按鈕的函數來實現逐步變化:
void GLWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) //按左鍵旋轉
{
mousehandle();
}
}
void GLWidget::mousehandle()
{
rTri += 5;
if (rTri > 360)
{
rTri -= 360;
}
this->updateGL();
}
整個cpp文件如下:
#include "glwidget.h"
#include "ui_glwidget.h"
#include <QtGui>
#include <QtCore>
GLWidget::GLWidget(QGLWidget *parent) :
QGLWidget(parent),
ui(new Ui::GLWidget)
{
ui->setupUi(this);
rTri = 0.0;
fullscreen = false;
}
void GLWidget::getScreenInfo() //得到當前計算機的屏幕分辨率
{
QDesktopWidget* desktopWidget = QApplication::desktop();
QRect screenRect = desktopWidget->screenGeometry();
g_nActScreenW = screenRect.width();
g_nActScreenH = screenRect.height();
}
void GLWidget::initializeGL() //初始化
{
setGeometry(0, 0, g_nActScreenW, g_nActScreenH);//設置窗口初始位置和大小
glShadeModel(GL_FLAT);//設置陰影平滑模式
glClearColor(0.0, 0.0, 0.0, 0);//改變窗口的背景顏色
glClearDepth(1.0);//設置深度緩存
glEnable(GL_DEPTH_TEST);//允許深度測試
glDepthFunc(GL_LEQUAL);//設置深度測試類型
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);//進行透視校正
}
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, 1.0, 0.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();
glLoadIdentity();
renderText(20, 100, "Hello Jcy, My first OpenGL app.");
}
//該程序是設置opengl場景透視圖,程序中至少被執行一次(程序啟動時).
void GLWidget::resizeGL(int width, int height)
{
if(0 == height)
height = 1;//防止一條邊為0
glViewport(0, 0, (GLint)width, (GLint)height);//重置當前視口,本身不是重置窗口的,只不過是這裡被Qt給封裝好了
glMatrixMode(GL_PROJECTION);//選擇投影矩陣
glLoadIdentity();//重置選擇好的投影矩陣
// gluPerspective(45.0, (GLfloat)width/(GLfloat)height, 0.1, 100.0);//建立透視投影矩陣
// glMatirxMode(GL_MODELVIEW);//以下2句和上面出現的解釋一樣
glLoadIdentity();
}
void GLWidget::keyPressEvent(QKeyEvent *e)
{
switch(e->key())
{
//F1鍵為全屏和普通屏顯示切換鍵
case Qt::Key_F1:
fullscreen = !fullscreen;
if(fullscreen)
showFullScreen();
else
{
setGeometry(0, 0, g_nActScreenW, g_nActScreenH);
showNormal();
}
updateGL();
break;
//Ese為退出程序鍵
case Qt::Key_Escape:
close();
}
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) //按左鍵旋轉
{
mousehandle();
}
}
void GLWidget::mousehandle()
{
rTri += 5;
if (rTri > 360)
{
rTri -= 360;
}
this->updateGL();
}
GLWidget::~GLWidget()
{
delete ui;
}