Skip to content

Add static SVG rendering through DrawingCanvas (SvgDocument, DrawSvg) - #442

Open
sebastienros wants to merge 1 commit into
SixLabors:mainfrom
sebastienros:svg-rendering
Open

sebastienros wants to merge 1 commit into
SixLabors:mainfrom
sebastienros:svg-rendering

Conversation

@sebastienros

@sebastienros sebastienros commented Nov 29, 2026 •

Copy link
Copy Markdown

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following matches the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules 👮.
  • I have provided test coverage for my change (where applicable)

Description

This adds static SVG rendering to ImageSharp.Drawing, as proposed in #435. An SVG document is loaded once into an immutable SvgDocument and drawn through the existing DrawingCanvas, so it works with every backend and needs no native code.

The branch is based on main at a4e94b8 (after #436) and follows the answers given in #435: the code lives in the existing package, the option types are init-only, gradients use AlphaRepresentation, and there is no ImageSharp decoder for .svg.

Public API

SvgDocument document = SvgDocument.Load(stream);            // or Load(path), Parse(text), each with SvgLoadOptions
using Image<Rgba32> image = new(800, 600);
image.Mutate(x => x.Paint(canvas => canvas.DrawSvg(document, new RectangleF(0, 0, 800, 600))));
  • SvgDocument (sealed): Load(Stream), Load(string), Parse(ReadOnlySpan<char>), each with an overload that takes SvgLoadOptions; Size, ViewBox. A loaded document does not change and can be drawn from any thread.
  • DrawingCanvas.DrawSvg(SvgDocument, PointF) and DrawSvg(SvgDocument, RectangleF).
  • SvgLoadOptions (init-only): Dpi, CurrentColor, Limits, UserStyleSheet, Languages, ResourceBaseDirectory, FontCollection, GenericFontFamilies, DefaultFontFamily, FallbackFontFamilies, CacheScenes.
  • SvgLimits (init-only): MaxElements, MaxNodes, MaxNestingDepth, MaxCharactersFromEntities, MaxImagePixels, MaxPatternTilePixels, MaxTextCharacters, MaxFilterPixels, MaxFilterTotalPixels, MaxLayerPixels, MaxSelectorTableBytes.
  • SvgGenericFontFamilies (init-only): the families behind serif, sans-serif, monospace, cursive, fantasy.

Everything else under src/ImageSharp.Drawing/Svg/ is internal. The changes outside that folder add no public members.

What is supported

  • Structure: svg, g, defs, symbol, use, switch, nested viewports, viewBox and preserveAspectRatio.
  • Shapes and paths, fill and stroke (dashes, caps, joins, markers, paint-order, vector-effect: non-scaling-stroke), linear and radial gradients, patterns.
  • clipPath, mask, opacity, mix-blend-mode, isolation, image (raster and nested SVG; data: URIs, and files only inside ResourceBaseDirectory).
  • Text: text, tspan, textPath, tref, anchoring, textLength, decorations, bidirectional text, vertical writing modes, font matching with fallback.
  • Filters: all 17 primitives of Filter Effects 1 and the CSS filter functions.
  • CSS: style sheets and style attributes, selectors level 4 (including :is(), :not(), :nth-child(... of S)), the cascade with !important, custom properties and var(), calc() and the other math functions, media queries, CSS Color 4 colors, CSS transforms and transform-box, CSS geometry properties, clip-path basic shapes.
  • Not supported: animation, scripting, interactivity, SVG fonts, network references, @import, @font-face, @supports, CSS nesting.

How it works

Load: parse (forward-only XmlReader into flat tables) → cascade → resolve (inheritance, units, use instances, geometry, paint servers, text layout) → an immutable list of draw nodes. Draw: the emitter turns the nodes into canvas commands. The document keeps the prepared scene of its last draws, so a repeated draw at the same size replays it (SvgLoadOptions.CacheScenes, on by default, bounded per document).

src/ImageSharp.Drawing/Svg/SVG_DESIGN.md describes the design, the measurements, and the known differences from browsers. SVG_DECISIONS.md lists the choices made on the way, each with its reason and what would change it.

Conformance

The tests run the resvg test suite (fetched by a script, not stored in the repository) and compare with its reference images under one tolerance for every renderer:

Tests run This PR resvg Chrome librsvg
All 1618 1179 (73%) 1522 1425 1170
Without the text tests 1278 1134 (89%) 1212 1146 1028

Of the 439 failures, 308 are text tests. 188 of those differ only in a half-pixel guide line of the test documents, which this rasterizer draws exactly and the reference renderer quantizes; the other large groups are reference images that differ from the specification and from Chromium, and cases where this renderer follows the specification where the reference does not. The table of every test with its reason is written by the test run.

Rendering choices that the specifications leave open follow the rendered output of Chromium. No source code of another renderer was read or ported; the bidirectional algorithm is a temporary copy of the internal one of SixLabors.Fonts (see below).

Performance

Measured with BenchmarkDotNet on a shared 4-core container against Svg.Skia, six documents at 1000 pixels, one pass (details and limits in SVG_DESIGN.md 22.7):

  • Load is 4 to 60 times faster than Svg.Skia.
  • A repeated draw of a loaded document is between 1.6 times faster and 1.7 times slower than the Svg.Skia picture replay with the default thread count.
  • A first draw is between 2.6 times faster (a document with 96 drop shadows) and 2 times slower (a dashboard with many small layers) with the default thread count; on one thread Svg.Skia is 1.7 to 2.8 times faster for five of the six documents.

Managed allocation is reported in the design document as an absolute value only; it is not compared with native renderers.

Untrusted input

  • XML: no resolver, so no external DTD or entity is read; entity expansion has a character limit.
  • No network access. Files are read only when the caller sets ResourceBaseDirectory, and only inside it; links are followed before the test. A nested SVG document reads no files.
  • Limits for elements, nodes after use expansion, nesting depth, image pixels, pattern tiles, filter images, layers, text length, and selector tables. A document over a limit throws InvalidImageContentException or renders at a lower resolution, as the limit documents.
  • Tests with hostile documents check that load and draw end in bounded time and memory.

Changes outside Svg/

28 source files, about 3,100 lines added. They are needed by the SVG code or were found while writing it:

  • Fixes. Path.TryParseSvgPath reads numbers with an exponent and starts the command after Z at the right point. A path clip no longer rasterizes a whole band of its geometry for every row. Edge cases in dash generation and curve flattening. A canvas from CreateRegion places gradient brushes, layer effects, and Apply in its own coordinates (CPU backend; the apply rectangle of the WebGPU backend needs the same change and is not touched, because I could not run it).
  • Speed, with unchanged output. Row loops for solid, gradient, and image brushes; reusable layer band buffers per worker; stored coverage of small fills in a retained scene, which the SVG scene cache uses; a partition count that follows the pixel count.
  • Internal hooks on DrawingCanvas and LayerEffect that the SVG emitter uses (recording a scene, mask effects that process layer rows in place).

One workaround remains: the emitter builds its own stroke outline under an enlarging transform that is not conformal, because of #439. A comment at that place says what to remove when #439 is fixed.

Tests

  • 7,149 tests pass and 155 are skipped; a Release build of the library and of the WebGPU project has no warnings.
  • The SVG tests are in tests/ImageSharp.Drawing.Tests/Svg: unit tests per parser and stage, reference-image tests (new images under tests/Images/ReferenceOutput, compared with renders of headless Chromium when they were added), hostile-document tests, and the conformance run above.
  • tests/SvgTools holds the scripts that fetch the suite and render reference images; tests/ImageSharp.Drawing.Benchmarks gets the SVG benchmarks and the comparison with Svg.Skia and NetVips.

For the reviewer

  • Size. 745 files: 287 new source files under Svg/ (about 60,000 lines), 86 test files, 328 test images and inputs. I can split it if that helps the review, for example the fixes outside Svg/ first.
  • Bidirectional text. Svg/Text/Bidi is a copy of the internal algorithm of SixLabors.Fonts 3.2.1, with a notice in THIRD-PARTY-NOTICES. It goes when Fonts exposes embedding levels for callers of TextShaper.ShapeRun.
  • Documents. The design document and the decision register are in src/ImageSharp.Drawing/Svg/ (about 3,400 lines of Markdown). I can move or remove them if they do not belong in the source tree.
  • Not run. The WebGPU backend: the SVG code draws through the canvas only, but nothing here was run on a GPU.

Related issues

Fixes #443
Fixes #444
Fixes #449

Related to #445: the CPU backend is corrected here; the apply rectangle of the WebGPU backend is not changed, so that issue stays open.

SvgDocument loads an SVG document once into an immutable form
(SvgDocument.Load and Parse, with SvgLoadOptions and SvgLimits), and
DrawingCanvas.DrawSvg draws it through the existing canvas, so it works
with every backend and needs no native code. The code is in
src/ImageSharp.Drawing/Svg; everything there except SvgDocument,
SvgLoadOptions, SvgLimits, and SvgGenericFontFamilies is internal.

Supported: document structure with use, symbol, switch, and nested
viewports; shapes, paths, strokes with dashes and markers; gradients
and patterns; clipPath, mask, opacity, and blend modes; images (data
URIs, and files inside SvgLoadOptions.ResourceBaseDirectory); text with
textPath, bidirectional text, and font fallback; the filter primitives
of Filter Effects 1 and the CSS filter functions; CSS style sheets with
selectors level 4, custom properties, math functions, media queries,
and CSS Color 4 colors. Not supported: animation, scripting, SVG fonts,
and network references.

The resvg test suite (fetched by tests/SvgTools, not stored in the
repository) passes 1179 of the 1618 tests that the test run includes.

Changes outside the Svg folder, with no new public members:

- Path.TryParseSvgPath reads numbers with an exponent and starts the
  command after Z at the right point.
- A path clip keeps the rows of its last band instead of rasterizing
  the band for every row.
- SplitPathExtensions.GenerateDashes and CubicBezierLineSegment end for
  geometry that they cannot walk or flatten.
- A canvas from CreateRegion places gradient brushes, layer effects,
  and Apply in its own coordinates (CPU backend).
- Row loops for solid, gradient, and image brushes; reusable layer
  band buffers; stored coverage of small fills in a retained scene.

src/ImageSharp.Drawing/Svg/SVG_DESIGN.md describes the design, the
measurements, and the known differences from browsers;
SVG_DECISIONS.md lists the choices made and their reasons.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant