Qt Snippet: Render SVG to QPixmap for high DPI screen

Convert a SVG image to QPixmap format is a very easy operation using the Qt classes. Common examples that is possible to find into documentation, however, refer to a situation where the screen device have standard pixel ratio of 1.



In case you need to show your picture in a screen with higher DPI ratio the result can be quite different. The following function get the path of an image file in SVG format and return a QPixmap sized as requested with the first param:

QPixmap FromSvgToPixmap(const QSize &ImageSize, const QString &SvgFile)
{
 QSvgRenderer SvgRenderer(SvgFile);
 QPixmap Image(ImageSize);
 QPainter Painter;

 Image.fill(Qt::transparent);

 Painter.begin(&Image);
 SvgRenderer.render(&Painter);
 Painter.end();

 return Image;
}

For a standard PC monitor this function will work as expected. The QSvgRenderer object will render the SVG image into QPixamp based to the pixmap size. However if you need to make same operation for a device with higher pixel ratio you'll note the image showed will appear more smaller than normal and not very well painted. This is because the image was rendered based to a pixel ratio of 1.0 but since the screen have higher pixel ratio the image will be "shrunkened" by keeping the real size. Fortunately the changes for adapt the render operation to the correct pixel ratio are not very complex as you can see below (changes are in red):

QPixmap FromSvgToPixmap(const QSize &ImageSize, const QString &SvgFile)
{
 const qreal PixelRatio = qApp->primaryScreen()->devicePixelRatio();
 QSvgRenderer SvgRenderer(SvgFile);
 QPixmap Image(ImageSize*PixelRatio);
 QPainter Painter;

 Image.fill(Qt::transparent);

 Painter.begin(&Image);
 SvgRenderer.render(&Painter);
 Painter.end();

 Image.setDevicePixelRatio(PixelRatio);

 return Image;
}

Basically the original requested image size was increased based to the current screen pixel ratio, the SVG was rendered into the image and after (this is important) the pixmap image was set with the same pixel ratio. This will have the result to show your image with correct logical size and well adapted to the screen type.

Comments

  1. Thank you! I wanted to screen grab widgets on 5k display.

    ReplyDelete

Post a Comment

Popular posts from this blog

Access GPIO from Linux user space

Launch an app from Android shell terminal

Qt 5 and " Failed to load platform plugin 'windows' " error