Load an SVG file with Resvg or fallback with Qt
| 268 | |
| 269 | // Load an SVG file with Resvg or fallback with Qt |
| 270 | QSize QtImageReader::load_svg_path(QString) { |
| 271 | bool loaded = false; |
| 272 | QSize default_size(0,0); |
| 273 | |
| 274 | // Calculate max image size |
| 275 | QSize current_max_size = calculate_max_size(); |
| 276 | |
| 277 | // Try to use libresvg for parsing/rasterizing SVG, if available |
| 278 | #if RESVG_VERSION_MIN(0, 11) |
| 279 | ResvgRenderer renderer(path, resvg_options); |
| 280 | if (renderer.isValid()) { |
| 281 | default_size = renderer.defaultSize(); |
| 282 | // Scale SVG size to keep aspect ratio, and fill max_size as much as possible |
| 283 | QSize svg_size = default_size.scaled(current_max_size, Qt::KeepAspectRatio); |
| 284 | auto qimage = renderer.renderToImage(svg_size); |
| 285 | image = std::make_shared<QImage>( |
| 286 | qimage.convertToFormat(QImage::Format_RGBA8888_Premultiplied)); |
| 287 | loaded = true; |
| 288 | } |
| 289 | #elif RESVG_VERSION_MIN(0, 0) |
| 290 | ResvgRenderer renderer(path); |
| 291 | if (renderer.isValid()) { |
| 292 | default_size = renderer.defaultSize(); |
| 293 | // Scale SVG size to keep aspect ratio, and fill max_size as much as possible |
| 294 | QSize svg_size = default_size.scaled(current_max_size, Qt::KeepAspectRatio); |
| 295 | // Load SVG at max size |
| 296 | image = std::make_shared<QImage>(svg_size, |
| 297 | QImage::Format_RGBA8888_Premultiplied); |
| 298 | image->fill(Qt::transparent); |
| 299 | QPainter p(image.get()); |
| 300 | renderer.render(&p); |
| 301 | p.end(); |
| 302 | loaded = true; |
| 303 | } |
| 304 | #endif // Resvg |
| 305 | |
| 306 | if (!loaded) { |
| 307 | // Use Qt for parsing/rasterizing SVG |
| 308 | image = std::make_shared<QImage>(); |
| 309 | loaded = image->load(path); |
| 310 | |
| 311 | if (loaded) { |
| 312 | // Set default SVG size |
| 313 | default_size.setWidth(image->width()); |
| 314 | default_size.setHeight(image->height()); |
| 315 | |
| 316 | if (image->width() < current_max_size.width() || image->height() < current_max_size.height()) { |
| 317 | // Load SVG into larger/project size (so image is not blurry) |
| 318 | QSize svg_size = image->size().scaled( |
| 319 | current_max_size, Qt::KeepAspectRatio); |
| 320 | if (QCoreApplication::instance()) { |
| 321 | // Requires QApplication to be running (for QPixmap support) |
| 322 | // Re-rasterize SVG image to max size |
| 323 | image = std::make_shared<QImage>(QIcon(path).pixmap(svg_size).toImage()); |
| 324 | } else { |
| 325 | // Scale image without re-rasterizing it (due to lack of QApplication) |
| 326 | image = std::make_shared<QImage>(image->scaled( |
| 327 | svg_size, Qt::KeepAspectRatio, Qt::SmoothTransformation)); |