如何将缩放的SVG渲染到QImage?

时间:2011-12-18 12:28:41

标签: image qt svg

QSvgRenderer模块中有一个QtSvg类,可以将图像渲染到QPaintDevice。这个可以是QImage。在这种情况下,我们将创建:

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

但是如何从SVG渲染器渲染到与默认大小不同的QImage?由于SVG格式图像可以在没有质量损失的情况下进行缩放,因此可以使用QSvgRenderer从SVG文件生成静态图像(如PNG)吗?

有没有人有更好的主意?基本上我需要从不同大小的SVG文件中创建像PNG这样的图像。

2 个答案:

答案 0 :(得分:42)

只需给出QImage所需的尺寸即可。 SVG渲染器将缩放以适合整个图像。

#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");
}

这将从传入的SVG文件中创建500x200 PNG图像。

带有SVG logos页面的SVG图像的示例输出:

enter image description here

答案 1 :(得分:3)

这是完整的答案:

QImage QPixmap::toImage() 

如果像素图具有1位深度,则返回的图像也将是1位深度。具有更多位的图像将以紧密代表底层系统的格式返回。对于没有alpha的pixmaps,对于带有alpha和QImage :: Format_RGB32或QImage :: Format_RGB16的pixmaps,通常会是QImage :: Format_ARGB32_Premultiplied。

QImage img = QIcon("filepath.svg").pixmap(QSize(requiredsize)).toImage()

同样从上面的答案中复制

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