OPenGL(三)平面图形上色

1.OpenGL.pro

QT += core gui opengl
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = OPenGL12
TEMPLATE = app

SOURCES += main.cpp\
    openglwidget.cpp

HEADERS  += \
    openglwidget.h

LIBS += -lopengl32

2.OpenglWidget

OpenglWidget.h

#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H
#include <QtOpenGL>
class OpenglWidget : public QGLWidget
{
public:
    OpenglWidget(QWidget *parent=0);
protected:
    void initializeGL();
    void initWidget();
    void paintGL();
    void resizeGL(int width, int height);
};

#endif // OPENGLWIDGET_H

OpenglWidget.cpp

#include "openglwidget.h"
OpenglWidget::OpenglWidget(QWidget *parent):QGLWidget(parent)
{
    initWidget();
    initializeGL();
}
void OpenglWidget::initializeGL()
{
    //设置着色模式,平滑的
    glShadeModel(GL_SMOOTH);
    //清除掉之前的所有颜色
    glClearColor(0.0,0.0,0.0,0.0);
    //深度缓存,设置初始值为1.0,小于1.0的部分是可见的
    glClearDepth(1.0);
    //启动OPenGL的相关功能,由参数决定,这里指
    //(启用了之后,OpenGL在绘制的时候就会检查,当前像素前面是否有别的像素,如果别的像素挡道了它,那它就不会绘制,也就是说,OpenGL就只绘制最前面的一层)
    glEnable(GL_DEPTH_TEST);
    //制定深度缓存比较值
    //这里参数指的是如果输入的深度值小于或者等于参考值则通过
    glDepthFunc(GL_LEQUAL);

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

}

void OpenglWidget::initWidget()
{
    //从屏幕上(400,400)为起始点,显示一个640*400的界面
    setGeometry(400,200,640,480);
    setWindowTitle("My OPenGL");
}

void OpenglWidget::paintGL()
{
    //清除颜色缓冲和深度缓冲
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    //将当前点移置屏幕中心,相当于复位的操作
    glLoadIdentity();
    //平移函数,参数指的是分别从X轴,Y轴,Z轴平移
    glTranslatef(-1.5,0.0,-6.0);
    //创建图元,是绘制什么图形的接口,参数是绘制多边形的意思
    glBegin(GL_QUADS);
    //设置顶点值(f代表浮点),三维空间坐标
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(-1.0,1.0,0.0);
    glColor3f(0.0,1.0,0.0);
    glVertex3f(1.0,1.0,0.0);
    glColor3f(0.0,0.0,1.0);
    glVertex3f(1.0,-1.0,0.0 );
    glColor3f(1.0,1.0,1.0);
    glVertex3f(-1.0,-1.0,0.0);
    glEnd();

    glTranslatef(3.0,0.0,0.0 );
    glColor3f(0.3,0.2,0.5);
    glBegin( GL_TRIANGLES );
    qDebug() << "this is a paintGL test!";
    glVertex3f(  0.0,  1.0,  0.0 );
    glVertex3f( -1.0, -1.0,  0.0 );
    glVertex3f(  1.0, -1.0,  0.0 );
    glEnd();

}

void OpenglWidget::resizeGL(int width, int height)
{
    if(0==height)
        height=1;
    //告诉绘制到窗体的哪个位置
    glViewport(0,0,width,height);
    // 设置矩阵模式,参数是设置为投影矩阵
    glMatrixMode(GL_PROJECTION);
    //复位操作
    glLoadIdentity();

    GLdouble aspectRatio=(GLfloat)width/(GLfloat)height;
    GLdouble rFov=45.0*3.14159265/180.0;
    GLdouble zNear=0.1;
    GLdouble zFar=100.0;
    //调用glFrustum,生成矩阵与当前矩阵相乘,生成透视效果
    glFrustum(-zNear*tan(rFov/2.0)*aspectRatio,
              zNear*tan(rFov/2.0)*aspectRatio,
              -zNear*tan(rFov/2.0),
              zNear*tan(rFov/2.0),
              zNear,zFar);
    //切回模型视图矩阵
    glMatrixMode(GL_MODELVIEW);
    //复位
    glLoadIdentity();
}

3.效果


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页