Parse, edit and render an SVG.
Parse, edit and render an SVG Parses an SVG from memory, finds an element by its data-* attribute, changes its style, and renders the document with the build's default renderer, saving output.png in the current working directory.
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <optional>
#include <string_view>
#include <utility>
if (const char* bwd = std::getenv("BUILD_WORKING_DIRECTORY")) {
std::filesystem::current_path(bwd);
}
constexpr std::string_view kSvg = R"(
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64">
<rect data-role="status" width="64" height="64" fill="gray" />
</svg>)";
std::cerr <<
"Parse Error: " << maybeDocument.
error() <<
"\n";
return 1;
}
std::optional<donner::svg::SVGElement> status = document.
querySelector(
"[data-role=status]");
if (!status) {
std::cerr << "No element has data-role=status\n";
return 1;
}
status->setStyle("fill: green");
if (!renderer.
save(
"output.png")) {
std::cerr << "Could not save output.png\n";
return 1;
}
return 0;
}
A parser result, which may contain a result of type T, or an error, or both.
Definition ParseResult.h:17
bool hasError() const noexcept
Returns true if this ParseResult contains an error.
Definition ParseResult.h:110
T & result() &
Returns the contained result.
Definition ParseResult.h:51
ParseDiagnostic & error() &
Returns the contained error.
Definition ParseResult.h:81
Collects parse warnings during parsing.
Definition ParseWarningSink.h:29
Backend-agnostic renderer that resolves to the active build backend (tiny-skia by default,...
Definition Renderer.h:82
RendererBitmap takeSnapshot() const override
Captures a CPU-readable snapshot of the current frame.
bool save(const char *filename)
Saves the last rendered frame to a PNG file.
void draw(SVGDocument &document) override
Draws the SVG document using the active backend.
Represents a parsed SVG document containing a tree of SVGElement nodes.
Definition SVGDocument.h:106
std::optional< SVGElement > querySelector(std::string_view selector)
Find the first descendant of the root <svg> element, in document order, that matches the given CSS se...
static ParseResult< SVGDocument > ParseSVG(std::string_view source, ParseWarningSink &warningSink, Options options={}, SVGDocument::Settings settings={}) noexcept
Parses an SVG XML document from a string (typically the contents of a .svg file).
int main()
Run the rendering example and report its result.
Definition render_test.cc:34
T y
The y component of the vector.
Definition Vector2.h:18
T x
The x component of the vector.
Definition Vector2.h:17
CPU-readable bitmap produced by a renderer snapshot.
Definition RendererInterface.h:67
Vector2i dimensions
Pixel dimensions of the bitmap in device pixels.
Definition RendererInterface.h:69