如何将缩放的 SVG 渲染为 QImage? [英] How to render a scaled SVG to a QImage?

查看:49
本文介绍了如何将缩放的 SVG 渲染为 QImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

解决方案

只需为您的 QImage 提供所需的大小.SVG 渲染器将缩放以适合整个图像.

#include #include #include <QPainter>#include //在您的 .pro 文件中://QT += SVGint main(int argc, char **argv){//如果在 SVG 中使用字体,则需要一个 QApplication 实例QApplication app(argc, argv);//加载你的SVGQSvgRenderer 渲染器(QString("./svg-logo-h.svg"));//准备一个具有所需特征的 QImageQImage 图像(500, 200, QImage::Format_ARGB32);图像填充(0xaaA08080);//部分透明的红色背景//获取绘制图像的 QPainterQPainter 画家(&image);renderer.render(&painter);//保存,基于文件扩展名的图片格式image.save("./svg-logo-h.png");}

这将根据传入的 SVG 文件创建一个 500x200 的 PNG 图像.

使用来自

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.

解决方案

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:

这篇关于如何将缩放的 SVG 渲染为 QImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆