Qt快速绘制像素点的处理方法

版权声明:所有的博客都是个人笔记,交流可以留言或者加QQ:2630492017 https://blog.csdn.net/qq_35976351/article/details/84990394

在有些情况下,我们需要对屏幕上的像素点进行大量的绘制操作。比如我之前模拟写的一个渲染管线开源练习,涉及到了大量的像素点操作。而Qt本身的QPen和QPainter::drawPoint的API如果操作大量的像素点,会非常耗时,因此我Google了这个方式:

原文链接:https://www.vikingsoftware.com/qwidget-pixel-drawing-2/

以下是核心代码:

#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QTime>
#include <QDebug>
const int loop = 25;
const int windowWidth = 400;
const int windowHeight = 300;
class PainterWindow : public QWidget {
    void paintEvent(QPaintEvent*) {
        QTime time;
        time.start();
        for (int i = 0; i < ::loop; ++i) {
            QPainter painter(this);
            for (int x = 0; x < width(); ++x) {
                for (int y = 0; y < height(); ++y) {
                    const QColor color(static_cast<QRgb>(i+x+y));
                    painter.setPen(color);
                    painter.drawPoint(x, y);
                }
            }
        }
        qDebug() << "drawPoint time:" << time.elapsed();
        close();
    }
};
 
class ImageWindow : public QWidget {
    void paintEvent(QPaintEvent*) {
        QRgb* pixels = new QRgb[width()*height()];
        QTime time;
        time.start();
        for (int i = 0; i < ::loop; ++i) {
            QPainter painter(this);
            QImage image((uchar*)pixels, width(), height(), QImage::Format_ARGB32);
            for (int x = 0; x < width(); ++x) {
                for (int y = 0; y < height(); ++y) {
                    pixels[x + y * height()] = static_cast<QRgb>(i+x+y);
                }
            }
            painter.drawImage(0, 0, image);
        }
        qDebug() << "drawImage time:" << time.elapsed();
        close();
        delete[] pixels;
    }
};
 
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    PainterWindow w;
    w.resize(::windowWidth, ::windowHeight);
    w.show();
 
    a.exec();
 
    ImageWindow imageWindow;
    imageWindow.resize(::windowWidth, ::windowHeight);
    imageWindow.show();
 
    a.exec();
}

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/84990394