zoukankan      html  css  js  c++  java
  • 绘图

    转: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();
    }

     

  • 相关阅读:
    MyEclipe 配置 ivy 插件
    PHP 向 MySql 中数据修改操作时,只对数字操作有效,非数字操作无效,怎么办?
    Hadoop 中 Eclipse 的配置
    Hadoop 配置好hive,第一次在conf能进入,第二次就不行了,怎么办?
    7系列FPGA远程更新方案-QuickBoot(转)
    Serial interface (RS-232)
    Linux下安装微信(转)
    《图解HTTP》读书笔记(转)
    《图解TCP/IP》读书笔记(转)
    7 Serial Configuration 理解(三)
  • 原文地址:https://www.cnblogs.com/Searchor/p/6756047.html
Copyright © 2011-2022 走看看