Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

image - How to render a scaled SVG to a QImage?

There is a QSvgRenderer class in QtSvg module which can render image onto QPaintDevice. This one can be QImage. In that case we will create:

Image svgBufferImage(renderer.defaultSize(), QImage::Format_ARGB32);

But how to render to a QImage of different size than default from the SVG renderer? Since the SVG format image can be scaled without quality loss, is it possible to generate static images, like PNG, from SVG files using QSvgRenderer?

Does anyone have a better idea? Basically I need to create images like PNG from SVG files in different sizes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just give your QImage the desired size. The SVG renderer will scale to fit the whole image.

#include <QApplication>
#include <QSvgRenderer>
#include <QPainter>
#include <QImage>

// In your .pro file:
// QT += svg 

int main(int argc, char **argv)
{
    // A QApplication instance is necessary if fonts are used in the SVG
    QApplication app(argc, argv);

    // Load your SVG
    QSvgRenderer renderer(QString("./svg-logo-h.svg"));

    // Prepare a QImage with desired characteritisc
    QImage image(500, 200, QImage::Format_ARGB32);
    image.fill(0xaaA08080);  // partly transparent red-ish background

    // Get QPainter that paints to the image
    QPainter painter(&image);
    renderer.render(&painter);

    // Save, image format based on file extension
    image.save("./svg-logo-h.png");
}

This will create an 500x200 PNG image from the passed in SVG file.

Example output with an SVG image from the SVG logos page:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...