1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4#include "svgimageprovider.h"
5#include <QImage>
6#include <QPixmap>
7#include <QSvgRenderer>
8#include <QPainter>
9
10QT_BEGIN_NAMESPACE
11
12SvgImageProvider::SvgImageProvider() :
13 QQuickImageProvider(QQuickImageProvider::Pixmap)
14{
15}
16
17SvgImageProvider::~SvgImageProvider()
18{
19}
20
21QPixmap SvgImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
22{
23 QSize imageSize(-1, -1);
24 QUrl request(id);
25 QString imagePath = QLatin1String(":/") + request.path();
26 if (request.hasQuery()) {
27 const QString query = request.query();
28 const QStringList paramList = query.split(sep: QLatin1Char('&'), behavior: Qt::SkipEmptyParts);
29 QVariantMap params;
30 for (const QString &param : paramList) {
31 QStringList keyValue = param.split(sep: QLatin1Char('='), behavior: Qt::SkipEmptyParts);
32 if (keyValue.size() == 2)
33 params[keyValue[0]] = keyValue[1];
34 }
35 const auto widthIt = params.constFind(key: QLatin1String("width"));
36 if (widthIt != params.cend()) {
37 bool ok = false;
38 int value = widthIt.value().toInt(ok: &ok);
39 if (ok)
40 imageSize.setWidth(value);
41 }
42 const auto heightIt = params.constFind(key: QLatin1String("height"));
43 if (heightIt != params.cend()) {
44 bool ok = false;
45 int value = heightIt.value().toInt(ok: &ok);
46 if (ok)
47 imageSize.setHeight(value);
48 }
49 } else {
50 imageSize = requestedSize;
51 }
52
53 QPixmap image;
54 if ((imageSize.width() > 0 || imageSize.height() > 0) && imagePath.endsWith(s: QLatin1String(".svg"))) {
55 QSvgRenderer renderer(imagePath);
56 QSize defaultSize(renderer.defaultSize());
57 if (defaultSize.isEmpty())
58 return image;
59 if (imageSize.width() <= 0 && imageSize.height() > 0) {
60 double aspectRatio = (double)defaultSize.width() / (double)defaultSize.height();
61 imageSize.setWidth(qRound(d: imageSize.height() * aspectRatio));
62 } else if (imageSize.width() > 0 && imageSize.height() <= 0) {
63 double aspectRatio = (double)defaultSize.width() / (double)defaultSize.height();
64 imageSize.setHeight(qRound(d: imageSize.width() / aspectRatio));
65 }
66 image = QPixmap(imageSize);
67 image.fill(fillColor: Qt::transparent);
68 QPainter painter(&image);
69 renderer.render(p: &painter, bounds: image.rect());
70 } else {
71 image = QPixmap(imagePath);
72 imageSize = image.size();
73 }
74
75 QPixmap result;
76 if (requestedSize.isValid() && requestedSize != imageSize)
77 result = image.scaled(s: requestedSize, aspectMode: Qt::KeepAspectRatio);
78 else
79 result = image;
80
81 *size = result.size();
82
83 return result;
84}
85
86QT_END_NAMESPACE
87

source code of qtvirtualkeyboard/src/styles/svgimageprovider.cpp