如何将缩放的SVG渲染到QImage? [英] How to render a scaled SVG to a QImage?
问题描述
QtSvg
模块中有一个 QSvgRenderer
类,它可以将图像渲染到 QPaintDevice
。这个可以是 QImage
。在这种情况下,我们将创建:
图像svgBufferImage(renderer.defaultSize(),QImage :: Format_ARGB32);
但是如何渲染到 QImage
SVG渲染器的大小与默认大小不同?由于SVG格式图像可以在没有质量损失的情况下进行缩放,是否可以使用 QSvgRenderer
从SVG文件生成静态图像,如PNG?
有没有人有更好的主意?基本上我需要从不同大小的SVG文件中创建像PNG这样的图像。
只需给你的 QImage
所需的大小。 SVG渲染器将缩放以适合整个图像。
#include< QApplication>
#include< QSvgRenderer>
#include< QPainter>
#include< QImage>
//在.pro文件中:
// QT + = svg
int main(int argc,char ** argv)
{
//如果在SVG
QApplication应用程序(argc,argv)中使用字体,则需要QApplication实例;
//加载你的SVG
QSvgRenderer渲染器(QString(./ svg-logo-h.svg));
//使用所需的characteritisc准备一个QImage
QImage图像(500,200,QImage :: Format_ARGB32);
image.fill(0xaaA08080); //部分透明的红色背景
//获取绘制图像的QPainter
QPainter画家(& 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屋!