使用QOffscreenSurface进行屏幕外渲染 - 带有Alpha笔颜色失败的QPainter

时间:2018-04-06 08:01:18

标签: qt opengl framebuffer off-screen

我已尝试this methodNikitaFeodonit的答案)进行屏幕外渲染并创建QImage并保存到磁盘。一切都运行正常,除了使用QColor和Alpha-Channel进行QPen。

QPainter.drawEllipse without ALPHA in Pen-Color

QPainter.drawEllipse with ALPHA in Pen-Color

这是我的来源:

使用this method中的OpenGlOffscreenSurface

标题ExamplePaintSurface.h

#ifndef EXAMPLEPAINTSURFACE_H
#define EXAMPLEPAINTSURFACE_H

#include <QPainter>
#include "OpenGlOffscreenSurface.h"

class ExamplePaintSurface
    : public OpenGlOffscreenSurface
{
public:
    explicit ExamplePaintSurface(
            QScreen* targetScreen = nullptr,
            const QSize& size = QSize (1, 1));

    void renderImage(bool useAlpha);

    virtual ~ExamplePaintSurface() override;

protected:
    virtual void initializeGL() override;

    virtual void resizeGL(
            int width,
            int height) override;

    virtual void paintGL() override;

private:
    bool m_useAlpha;
};


#endif  // EXAMPLEPAINTSURFACE_H

来源ExamplePaintSurface.cpp

#include "ExamplePaintSurface.h"

ExamplePaintSurface::ExamplePaintSurface(
        QScreen*     targetScreen,
        const QSize& size)
    : OpenGlOffscreenSurface(targetScreen, size) {}

void ExamplePaintSurface::renderImage(bool useAlpha)
{
    m_useAlpha = useAlpha;
    this->paintGL();
}


ExamplePaintSurface::~ExamplePaintSurface() {}


void ExamplePaintSurface::initializeGL() {}


void ExamplePaintSurface::resizeGL(int width, int height) {}


void ExamplePaintSurface::paintGL()
{
    QPainter painter(getPaintDevice());
    painter.eraseRect(0,0,200,200);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setCompositionMode (QPainter::CompositionMode_Source);
    painter.fillRect(0,0,200,200, Qt::transparent);
    painter.setCompositionMode (QPainter::CompositionMode_SourceOver);

    QPen pen;
    if(m_useAlpha == true)
        pen.setColor(QColor(255, 0, 0, 150));
    else
        pen.setColor(QColor(255, 0, 0, 255));
    QBrush brush(Qt::yellow);
    brush.setStyle(Qt::SolidPattern);
    pen.setWidth(8);
    painter.setPen(pen);
    painter.setBrush(brush);
    painter.drawEllipse(50,50,100,100);

    //painter.drawText(20, 40, "Test"); // <-- drawing here

    painter.end();
}

来源main.cpp

#include <QApplication>
#include "ExamplePaintSurface.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    ExamplePaintSurface paintSurface;
    paintSurface.resize(200, 200);
    paintSurface.renderImage(false);
    paintSurface.render();
    QImage image = paintSurface.grabFramebuffer();
    image.save("Ellipse_noAlpha.png");

    paintSurface.renderImage(true);
    paintSurface.render();
    image = paintSurface.grabFramebuffer();
    image.save("Ellipse_alpha.png");

    return a.exec();
}

0 个答案:

没有答案