How to render a scaled SVG to a QImage?

前端 未结 2 1310
一整个雨季
一整个雨季 2020-12-01 06:55

There is a QSvgRenderer class in QtSvg module which can render image onto QPaintDevice. This one can be QImage. In that c

2条回答
  •  感动是毒
    2020-12-01 07:05

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

    #include 
    #include 
    #include 
    #include 
    
    // 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:

提交回复
热议问题