Keep aspect ratio when rendering SVG images

Also, allow to add margin to the pixmap.
This commit is contained in:
Martchus 2019-02-27 20:38:14 +01:00
parent b0c4c122a4
commit c7927c3f2e
2 changed files with 21 additions and 9 deletions

View File

@ -9,13 +9,26 @@ namespace Data {
/// \cond
namespace Detail {
template <typename SourceType> QPixmap renderSvgImage(const SourceType &source, const QSize &size)
template <typename SourceType> QPixmap renderSvgImage(const SourceType &source, const QSize &size, int margin)
{
QSvgRenderer renderer(source);
QSize renderSize(renderer.defaultSize());
renderSize.scale(size.width() - margin, size.height() - margin, Qt::KeepAspectRatio);
QRect renderBounds(QPoint(), size);
if (renderSize.width() < renderBounds.width()) {
const auto diff = (renderBounds.width() - renderSize.width()) / 2;
renderBounds.setX(diff);
renderBounds.setWidth(renderSize.width());
}
if (renderSize.height() < renderBounds.height()) {
const auto diff = (renderBounds.height() - renderSize.height()) / 2;
renderBounds.setY(diff);
renderBounds.setHeight(renderSize.height());
}
QPixmap pm(size);
pm.fill(QColor(Qt::transparent));
QPainter painter(&pm);
renderer.render(&painter, pm.rect());
renderer.render(&painter, renderBounds);
return pm;
}
} // namespace Detail
@ -26,17 +39,17 @@ template <typename SourceType> QPixmap renderSvgImage(const SourceType &source,
* \remarks If instantiating QIcon directly from SVG image the icon is not displayed in the tray under Plasma 5. It works
* with Tint2, however.
*/
QPixmap renderSvgImage(const QString &path, const QSize &size)
QPixmap renderSvgImage(const QString &path, const QSize &size, int margin)
{
return Detail::renderSvgImage(path, size);
return Detail::renderSvgImage(path, size, margin);
}
/*!
* \brief Renders an SVG image to a QPixmap.
*/
QPixmap renderSvgImage(const QByteArray &contents, const QSize &size)
QPixmap renderSvgImage(const QByteArray &contents, const QSize &size, int margin)
{
return Detail::renderSvgImage(contents, size);
return Detail::renderSvgImage(contents, size, margin);
}
/*!

View File

@ -10,9 +10,6 @@ QT_FORWARD_DECLARE_CLASS(QColor)
namespace Data {
QPixmap LIB_SYNCTHING_MODEL_EXPORT renderSvgImage(const QString &path, const QSize &size = QSize(128, 128));
QPixmap LIB_SYNCTHING_MODEL_EXPORT renderSvgImage(const QByteArray &contents, const QSize &size = QSize(128, 128));
QByteArray LIB_SYNCTHING_MODEL_EXPORT loadFontAwesomeIcon(const QString &iconName, const QColor &color);
struct StatusIcons {
@ -29,6 +26,8 @@ struct StatusIcons {
QIcon newItem;
};
QPixmap LIB_SYNCTHING_MODEL_EXPORT renderSvgImage(const QString &path, const QSize &size = QSize(128, 128), int margin = 0);
QPixmap LIB_SYNCTHING_MODEL_EXPORT renderSvgImage(const QByteArray &contents, const QSize &size = QSize(128, 128), int margin = 0);
const StatusIcons LIB_SYNCTHING_MODEL_EXPORT &statusIcons();
} // namespace Data