开发者

How to draw & export a transparent image with Nokia Qt C++?

开发者 https://www.devze.com 2022-12-15 13:26 出处:网络
I have a piece of code intended for drawing & exporting a transparent image with Nokia Qt. However, it does not work. I always see black background with lots of noise. I must fill the background w

I have a piece of code intended for drawing & exporting a transparent image with Nokia Qt. However, it does not work. I always see black background with lots of noise. I must fill the background with White color but I want transparency, not white color. Please kindly advise.

#include <QtGui/QApplication>
#include <QtGui>

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

    {
        QImage pix(260, 50, QImage::Format_ARGB32_Premultiplied);

        QPainter painter(&pix);
        painter.setBackgroundMode(Qt::TransparentMode);
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::TextAntialiasing开发者_如何转开发, true);
        painter.setPen(QColor(0x00, 0x00, 0x00, 0xff));
        painter.setBrush(QColor(0x00, 0x00, 0x00, 0xff));
        painter.setFont(QFont("AvantGarde Md BT", 32));
        painter.setBackgroundMode(Qt::TransparentMode);

        // I don't like the white color, but I must put otherwise you'll see dumb & black background
        painter.fillRect(0, 0, pix.width(), pix.height(), QColor(0xff, 0xff, 0xff, 0xff));

        QString text("My Text");
        QFontMetrics fm(painter.font());

        int w = fm.width(text);
        int h = fm.height();

        painter.drawText((pix.width() - w)/2, (pix.height() + h/2)/2, text);
        pix.save(QString("mytext.png"));
    }
}


I found answer by myself:

I just have to add one magic line right after declaration of the pix:

pix.fill(Qt::transparent);

References:

http://techbase.kde.org/Development/Tutorials/Graphics/Performance

http://www.informit.com/articles/article.aspx?p=1174421&seqNum=3

0

精彩评论

暂无评论...
验证码 换一张
取 消