1 xtk_svg
liquibyte edited this page 2026-11-19 16:23:20 -06:00

xtk_svg.h

Renders SVG documents, such as icons, into RGBA8 images.

This module parses an SVG document with xtk_xml.h and draws it with xtk_vector.h into a new image in memory. It needs no X connection. It is made for icons and small drawings: xtk_icon.h uses it for SVG icon themes, and a program can use it for its own artwork.

Use. Call xtk_svg_render_file() or xtk_svg_render_memory() with the size you want. The document's viewBox is scaled by the same factor in both directions so that it fits the image, and is centered (the SVG default "xMidYMid meet"). The image comes back in an XtkSvgImage, which the caller frees with xtk_svg_image_free(). To ask for the document's own size first, call xtk_svg_get_intrinsic_size().

Recoloring. Many icon sets draw with currentColor. Pass a color as current_color_override to make those parts that color, for example the theme's text color, so that one icon file fits every theme.

What it draws.

  • The elements svg (nested ones too, each a viewport of its own), g, a, switch, use (of any element, a symbol or an svg), path, rect (with rounded corners), circle, ellipse, line, polyline, polygon, image and text (with tspan). Other elements are not drawn, but their children are; elements of other namespaces (Inkscape's, Sodipodi's, metadata) are left out.
  • All path commands, including elliptical arcs and the smooth curve commands.
  • The transform attribute (matrix, translate, scale, rotate, skewX, skewY) on any element, viewBox and preserveAspectRatio on the root, on an inner svg, a symbol, a marker, a pattern and an image.
  • Lengths in px, pt, pc, mm, cm, in, em and ex, and percentages of the viewport.
  • Style sheets in <style> elements, with rules by element, class (.name), id (#name), attribute ([name], [name=value]) and :root, and the descendant and child combinators. The cascade is as CSS's: the style attribute, then the rules that fit (the most specific, then the last), then the presentation attributes. !important is read but not ranked higher.
  • Paint: colors (#rgb, #rgba, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl(), hsla(), every CSS color name, transparent, currentColor and none), linear and radial gradients (with gradientUnits, gradientTransform, spreadMethod, focal points, and attributes and stops inherited through href), patterns, solid colors (solidColor), and a fallback color after url(#id). An id in a URL may be percent-encoded.
  • The color property: what currentColor is for an element and what it holds. The document starts with the color the caller gives, and an element can change it (icon themes color themselves this way).
  • fill-opacity, stroke-opacity, fill-rule, stroke-width, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-dasharray, stroke-dashoffset, display and visibility, as attributes or in style. Children inherit what CSS says they inherit.
  • In a layer of its own, then merged into the drawing: opacity, clip-path (with clipPathUnits and clip-rule), mask (luminance or mask-type: alpha, with its region and units), filter and mix-blend-mode (the separable modes: multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference and exclusion).
  • Filters: feGaussianBlur, feOffset, feFlood, feComposite (with arithmetic), feMerge, feBlend, feColorMatrix, feComponentTransfer, feMorphology and feDropShadow, in linearRGB or sRGB as color-interpolation-filters says, within the filter region and each primitive's subregion.
  • Markers (marker-start, marker-mid, marker-end and marker) on paths, lines, polylines and polygons, with orient, refX, refY and markerUnits.
  • Images: PNG, JPEG, GIF, BMP or SVG, in a data: URL or in a file beside the document (xtk_svg_render_file() knows where that is). Nothing is fetched from a network. A file that is not there draws nothing.
  • Text in the font Fontconfig finds for its font-family, font-weight and font-style, in UTF-8, with tspan positions (x, y, dx, dy), text-anchor, letter-spacing, kerning and xml:space.
  • Entities a DOCTYPE declares (xtk_xml.h), and documents compressed with gzip (.svgz).

Example.

XtkVectorColor ink = {220, 220, 220, 255};
XtkSvgImage image = {0};
if (xtk_svg_render_file("icons/save.svg", 24, 24, &ink, &image)) {
    // image.pixels holds 24 x 24 RGBA8 pixels
    xtk_svg_image_free(&image);
}
 * 

Limitations.

  • Not drawn: the non-separable blend modes (hue, saturation, color, luminosity, drawn as normal), the filters feTile, feImage, feTurbulence, feConvolveMatrix, feDisplacementMap and the lighting ones (each passes its input on), paint-order, vector-effect, the CSS sibling combinators and the other pseudo-classes (a rule with them never fits), text on a path (drawn as plain text), a list of positions for each character (the first one counts), vertical text, and animation.
  • Overflow is not clipped: a marker, a pattern tile or an inner svg draws past its viewport.
  • Against loops and runaway documents: elements nest at most 64 deep, a use, pattern, mask, marker or image within another at most 12, a pattern is never drawn within itself, a document draws at most 65,536 pattern tiles, a text keeps 8,192 characters for each run, an image is at most 4096 pixels across, and a filter keeps 32 named results (a name used again takes the place of the one before).
  • The renderer keeps the current color, the document's style sheet and ids, and the fonts in static variables, so it must be called from one thread at a time.
#include "xtk_svg.h"

Types: XtkSvgImage

Functions: xtk_svg_render_memory, xtk_svg_render_file, xtk_svg_get_intrinsic_size, xtk_svg_image_free

Types

XtkSvgImage

An RGBA8 image rendered from an SVG document.

Field Type Description
pixels unsigned char * The pixels: R, G, B, A bytes, row by row from the top, straight alpha (the layout of xtk_image_load_rgba8()). Freed by xtk_svg_image_free().
width int The width in pixels.
height int The height in pixels.

Functions

xtk_svg_render_memory

int xtk_svg_render_memory(
    const char *data,
    size_t size,
    int target_width,
    int target_height,
    const XtkVectorColor *current_color_override,
    XtkSvgImage *out);

Renders an SVG document held in memory into a new RGBA8 image.

The image's width is target_width when that is greater than 0, else the document's own width (rounded up); the same goes for the height. The document's own size comes from the width and height attributes of the svg element, else from its viewBox, else it is 300 x 150. The viewBox is scaled by one factor so that it fits the image, and centered; the rest of the image stays transparent.

Parameter Description
data The SVG document. It need not end with a NUL byte.
size The length of data in bytes.
target_width The image's width in pixels, or 0 or less for the document's own width.
target_height The image's height in pixels, or 0 or less for the document's own height.
current_color_override The color that currentColor stands for, or NULL for opaque black.
out Receives the image. The caller frees it with xtk_svg_image_free().

Returns: 1 when the image was rendered into out; 0 when data or out is NULL, size is 0, the XML cannot be parsed, there is no svg element at the top level, or memory runs out. On 0, out is not changed.

xtk_svg_render_file

int xtk_svg_render_file(
    const char *path,
    int target_width,
    int target_height,
    const XtkVectorColor *current_color_override,
    XtkSvgImage *out);

Renders an SVG file into a new RGBA8 image.

This reads the whole file and then works as xtk_svg_render_memory(). Compressed .svgz files are not read.

Parameter Description
path The path of the SVG file.
target_width The image's width in pixels, or 0 or less for the document's own width.
target_height The image's height in pixels, or 0 or less for the document's own height.
current_color_override The color that currentColor stands for, or NULL for opaque black.
out Receives the image. The caller frees it with xtk_svg_image_free().

Returns: 1 when the image was rendered into out; 0 when path or out is NULL, the file cannot be read, or xtk_svg_render_memory() fails. On 0, out is not changed.

xtk_svg_get_intrinsic_size

int xtk_svg_get_intrinsic_size(
    const char *data,
    size_t size,
    double *width_out,
    double *height_out);

Gives an SVG document's own size without rendering it.

The size is read as xtk_svg_render_memory() reads it: the width and height attributes of the svg element, else its viewBox, else 300 x 150. The document is still parsed, so this is not free, but it draws nothing.

Parameter Description
data The SVG document. It need not end with a NUL byte.
size The length of data in bytes.
width_out Receives the width in user units; may be NULL.
height_out Receives the height in user units; may be NULL.

Returns: 1 when the size was written; 0 when data is NULL, size is 0, the XML cannot be parsed or there is no svg element at the top level.

xtk_svg_image_free

void xtk_svg_image_free(XtkSvgImage *image);

Frees an image's pixels and sets its fields to 0.

The XtkSvgImage itself belongs to the caller. Calling this on an image that is all zeros, or twice on the same image, is allowed.

Parameter Description
image The image. NULL is allowed and does nothing.