31. SVG images and the image viewer#
lib/img_svg reads SVG files (a practical SVG 1.1 / SVG Tiny subset)
and draws them through gfx's path rasterizer: sharp at every size, no libc. A document is
parsed once into an immutable Svg and drawn as often as needed. The UI shows it with
ui.svg (pictures and icons at their layout size) or ui.image_view (zoom and pan); the
runtime also registers it as the image format IMGF_SVG, so img_core::io::load /
load_ex / decode_ex return .svg and .svgz files as bitmaps of their intrinsic size.
// once: parse (UTF-8 XML; gzip data of .svgz is inflated); Err(img_core::ERR_*)
let Some(data) = plat::read_file("app://art/logo.svg") else { return };
let Ok(doc) = ui::Svg::parse(&data) else { return };
let doc = Rc::new(doc);
let (w, h) = doc.size(); // intrinsic px: width / height, else the viewBox
// per frame: a picture at 64 DIP wide (height from the aspect ratio), drawn at render time
// at the device size; currentColor = the theme's text colour; K_IMAGE with its <title>
ui.svg(ID_LOGO, &doc, 64, 0);
// a bitmap of any size, outside the UI (no text: Opts::default() has no font engine)
let sf = doc.rasterize(256, 256, &mut img_svg::Opts::default())?;
- Drawing yourself (a canvas
Draw):doc.render_rect(g.sf, x, y, w, h, Some(g.dc.clip), &mut opts)maps the viewBox into the rectangle (preserveAspectRatio);doc.render(sf, &matrix, clip, &mut opts)draws the intrinsic size through any matrix (zoomed, rotated).Opts { color, text }: the colour ofcurrentColor, and the font engine for<text>:ui::SvgText { text: g.text, fonts: &fonts }(fonts =ui.svg_fonts(), taken at frame time into theDrawobject) sets text with the UI's fonts (families registered withui.font_register,monospace=ui.mono_font_set, everything else the style's fonts; italic is slanted). Without a font engine text is skipped. - Supported:
svg(nested viewports),g,defs,use+symbol,switch(its first child),a;path(every command, arcs),rect(rx / ry),circle,ellipse,line,polyline,polygon; transforms; fill / stroke with colours (hex,rgb(),hsl(), the 148 names,currentColor), opacities, fill-rule, width / caps / joins / miter limit / dashes; linear and radial gradients (stops, units, transform, spread, focal point,hrefinheritance);opacityof groups (layers);clipPath;display,visibility;<style>sheets (type, class, id and attribute selectors, descendant and child combinators), thestyleattribute, presentation attributes,inherit; lengths in px / pt / pc / mm / cm / in / em / ex / %;text/tspan(one line per chunk, x / y / dx / dy, text-anchor, font size / weight / style / family);imagewithdata:URIs of the registered raster formats. Not supported (drawn without):pattern(its fallback colour is used),mask,marker,filter, text on paths, per-glyph positions, external files, CSS pseudo-classes and@media, animation, scripts. - Robustness: malformed files never panic; the reader is forgiving (unclosed tags, unquoted
attributes, a broken path draws up to the error,
svg.truncated()tells). Limits: 32 MB per file (also inflated), 250 000 elements, 256 levels, entity references expand once (no exponential growth),usecycles are cut, a step budget for CSS selectors and 128 MB of declarations the cascade copies (beyond:ERR_LIMIT), and per render 1 000 000 element visits, a work budget (pixels painted, layers and masks, path points: 64 per pixel drawn, at least 2^26) and 64 levels of nesting.
The image viewer shows a bitmap or an SVG in a zoomable, scrollable view; the app keeps an
ImageViewState:
// state: self.view = ImageViewState::default(); (fit mode at first)
let ev = ui.image_view(ID_VIEW, &mut self.view, ViewImage::Bitmap(&self.photo, self.photo_ver), 0);
// or ViewImage::Svg(&self.doc): drawn again at every zoom, only the visible part
if ev & EV_ACT != 0 {
self.status = format!("{} %", self.view.zoom_pct()); // zoom or position changed
}
if ui.button(ID_FIT, "Einpassen") & EV_ACT != 0 { self.view.set_fit(); }
if ui.button(ID_ONE, "100 %") & EV_ACT != 0 { self.view.set_actual(); }
zoom1.0 = 100 %: a bitmap pixel on one screen pixel, an SVG at its intrinsic size in DIP;cx,cy= the image point at the view's centre;fit= the zoom follows the view.zoom_to([x, y, w, h])shows an image rectangle,zoom_by(f)multiplies,labelnames the view for screen readers (default: the SVG's title or "Bild"; the record's value is the zoom in percent). Another image (anotherRc) starts in fit mode again.- Mouse: the wheel zooms at the pointer (the image point under it stays), Shift + wheel
scrolls sideways; a left or middle drag pans; Ctrl + drag zooms into a rectangle; a double
click switches between 100 % and fit; the scroll bars at the edges move the view. Keys:
arrows, PgUp / PgDn, Home / End pan; + / - zoom in steps (1 % .. 6400 %); Ctrl+0 fits;
Ctrl+1 shows 100 %. Flags:
IV_WHEEL_SCROLL(the wheel scrolls, Ctrl + wheel zooms; for views inside scrolled pages),IV_SMOOTH(no visible pixels),IV_NO_GRID,IV_NO_BARS,IV_NO_CHECKER,IV_TEXT_COLOR(an SVG's currentColor follows the theme). - Drawing: bitmaps below 50 % through mip levels (2 x 2 box), bilinear up to 400 %, nearest neighbour above, a pixel grid from 800 %; transparency over a checkerboard (plain background in high contrast).
- Tests:
apps/svgtest(--test unit: 321 checks of parser, path data, transforms, gradients, text layout (with a font engine of boxes), clipping, CSS, the codec and malformed files;gallery.uis: every fixture ofapps/svgtest/fixtureslight / dark / high contrast / 200 %;viewer.uis,viewer_modes.uis: zoom and pan by script, all with--verify-dirty).