绘图

转:http://blog.csdn.net/wangpingfang/article/details/8141635

对于大多数Qt应用,我们在QWidget的paintEvent方法中创建和构造一个QPainter画图,或者在QGLWidget中的paintGL使用OpenGL函数画图,这是最常见的使用方式,并且基本能够满足应用需求。但是这把画图操作限制在了某一个方法之中,考虑一个这样的场景:客户想生成某个字体的字符图片,并把这些图片保存起来。在这个应用场景下,完全没有必要创建一个GUI应用,然后在paintEvent中画图,而只需要在一个控制台应用中,在内存中画图即可。

接下来我将介绍两种使用Qt在内存中画图的方法:使用QPainter和使用OpenGL。

 使用QPainter

QPainter能够在QWidget和其他的画图设备(paintdevice,当然QWidget也是一种paint device)进行绘制操作。如果想要在内存中画图,那么就得创建一个内存画图设备,Qt中,QPixmap刚好满足这个要求,废话不多说,直接看代码吧:

#include <QtGui/QApplication>
#include <Windows.h>
#include <QtGui/QPixmap>
#include <QtGui/QPainter>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // 创建一个画图设备
    QPixmap pixmap(100, 100);
    QPainter painter;
    painter.begin(&pixmap);
    painter.drawText(10, 45, QString::fromLocal8Bit("I love American."));
    painter.end();
    pixmap.save(QString::fromLocal8Bit("pixmap.png"));

    return a.exec();
}

使用OpenGL

在GUI应用中,OpenGL在QGLWidget中进行绘制操作,在这个场景下,QGLWidget就相当于一个画图设备,只不过执行绘制操作的是OpenGL函数,而不是QPainter。如果想要在内存中使用OpenGL画图,同样也得创建一个与QGLWidget对应的内存画图设备,Qt中,QGLPixelBuffer满足这个要求,下面我们来看看代码:

#include <QtGui/QApplication>
#include <Windows.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <QtOpenGL/QGLFormat>
#include <QtOpenGL/QGLPixelBuffer>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    
    // Construct an OpenGL pixel buffer.
    QGLPixelBuffer glPixBuf(100, 100); 
    // Make the QGLContext object bound to pixel buffer the current context
    glPixBuf.makeCurrent();
    // The opengl commands 
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glViewport(0, 0, 100, 100);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, 100, 0, 100);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 0.0, 0.0);
    glPointSize(4.0);
    glBegin(GL_TRIANGLES);
    glVertex2i(10, 10);
    glVertex2i(50, 50);
    glVertex2i(25, 75);
    glEnd();
    // At last, the pixel buffer was saved as an image
    QImage &pImage = glPixBuf.toImage();
    pImage.save(QString::fromLocal8Bit("gl.png"));
    
    return a.exec();
}

 

原文地址:https://www.cnblogs.com/Searchor/p/6756047.html