svg

package
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package svg is Silk's SVG rendering layer — the equivalent of Qt's QSvgRenderer. It parses SVG XML into a small AST and renders the AST through silk/paint.Painter, so the same drawing pipeline used by every Silk widget also handles SVG icons.

Scope: the parser handles the dominant subset of SVG used in icon art — rect / circle / ellipse / line / polygon / polyline / path shapes, group nesting, basic transforms (translate / scale / rotate / matrix), and the Style attributes fill / stroke / stroke-width / opacity / fill-rule. Out of scope:

  • text (<text>, <tspan>) — Silk widgets typically render text through paint.Painter directly anyway
  • filters, clip paths, masks, gradients (defer to a follow-up)
  • SMIL animation (Silk's animation system runs imperatively)
  • external image refs (<image href=...>)

Typical usage:

doc, err := svg.Parse(data)
svg.Render(doc, painter, 24, 24) // render into a 24x24 region

Style inheritance: cascading style is implemented via stack-based state during render. A child whose attribute is unspecified inherits from its parent group. The standard SVG "presentation attributes" are recognised on every shape; the CSS-in-style="" form is also parsed.

Intentionally tiny: we don't pull in a third-party SVG dep. The dominant icon-art path is well within the parser's reach, and the surface area stays under ~800 LOC so future maintenance is cheap.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Render

func Render(doc *Doc, painter paint.Painter, x, y, w, h float64)

Render draws doc onto painter, scaled into the target rectangle (x, y, w, h) in painter coordinates. The doc's ViewBox is mapped to the target rect; if no ViewBox is set, doc.Width/doc.Height are used; if those are also zero, the target rect is treated as the 1:1 source.

The painter must be in a state ready for path operations — the caller is responsible for any clip / transform setup the surrounding widget needs. Render saves and restores state internally so the painter's CTM and brush/pen are unchanged on return.

Types

type Circle

type Circle struct {
	Common
	Cx, Cy, R float64
}

Circle is a centered circle.

type Color

type Color struct {
	None bool
	Val  paint.Color
}

Color is a wrapper carrying the explicit-vs-none distinction. SVG's "none" is structurally different from "transparent black" — a shape with fill="none" doesn't fill at all (no SetBrush call), while fill="black; opacity:0" still calls Fill but with zero alpha.

type Common

type Common struct {
	Style     Style
	Transform Transform
}

Common holds the style + transform that every shape supports. We embed it rather than duplicate fields in each Shape variant.

type Doc

type Doc struct {
	Width    float64
	Height   float64
	ViewBox  ViewBox
	Children []Shape
}

Doc is the parsed SVG tree. ViewBox defines the coordinate system the shapes are drawn in; Width/Height are the document's intrinsic size. Render maps ViewBox to the target rectangle.

When Width/Height are zero the renderer falls back to ViewBox dimensions; when ViewBox is zero too, it defaults to the target rect. This matches what major SVG icon sets ship.

func Parse

func Parse(data []byte) (*Doc, error)

Parse decodes SVG bytes into a Doc tree. Returns an error on malformed XML or any structural problem with the root <svg> element. Unknown child elements are silently skipped — partial-support degradation matches what every browser does with unfamiliar SVG features.

Coordinate normalisation: every path "d" attribute is decoded into absolute commands at parse time; the renderer doesn't need to maintain a "current point" outside of the path it's rendering.

func ParseString

func ParseString(s string) (*Doc, error)

ParseString is a convenience for the common case of parsing a Go string literal SVG (e.g. an embedded icon resource).

type Ellipse

type Ellipse struct {
	Common
	Cx, Cy, Rx, Ry float64
}

Ellipse is a centered ellipse with two radii.

type FillRule

type FillRule int

FillRule mirrors SVG's nonzero / evenodd. 0 = inherit.

const (
	FillRuleInherit FillRule = iota
	FillRuleNonzero
	FillRuleEvenOdd
)

type Group

type Group struct {
	Common
	Children []Shape
}

Group is a <g> element with nested children. Its Common style / transform cascades onto every descendant via the renderer's stack.

type Line

type Line struct {
	Common
	X1, Y1, X2, Y2 float64
}

Line is a single segment.

type Path

type Path struct {
	Common
	Commands []PathCmd
}

Path is the fully general shape with a list of low-level commands produced by the path-data parser. PathCmd union below.

type PathCmd

type PathCmd struct {
	Kind PathCmdKind
	// Move / Line: X, Y
	// CurveTo: X1, Y1 (control1), X2, Y2 (control2), X, Y (end)
	// QuadTo:  X1, Y1 (control), X, Y (end)
	// Arc: X1=rx, Y1=ry, X2=xRot, A=largeArcFlag, B=sweepFlag, C=x, D=y
	// Close: no fields
	X, Y, X1, Y1, X2, Y2 float64
	A, B, C, D           float64
}

PathCmd is one command from an SVG path "d" attribute. We normalise every command to absolute coordinates at parse time so the renderer can dispatch without per-command relative bookkeeping.

type PathCmdKind

type PathCmdKind int

PathCmdKind enumerates the command set we honour. SVG's full set is MmLlHhVvCcSsQqTtAaZz but we normalise H/V into L and convert all to absolute, so the runtime kinds collapse into the five below.

const (
	PathMove PathCmdKind = iota + 1
	PathLine
	PathCurve
	PathQuad
	PathArc
	PathClose
)

type Point

type Point struct{ X, Y float64 }

Point is a single (x, y) used by Polygon / Polyline.

type Polygon

type Polygon struct {
	Common
	Points []Point
}

Polygon is a closed polyline.

type Polyline

type Polyline struct {
	Common
	Points []Point
}

Polyline is an open polyline (no closing edge).

type Rect

type Rect struct {
	Common
	X, Y, W, H float64
	Rx, Ry     float64
}

Rect renders an axis-aligned rectangle, optionally with rounded corners (Rx / Ry).

type Shape

type Shape interface {
	// contains filtered or unexported methods
}

Shape is the sealed interface every drawable element implements. The renderer type-switches on the concrete type to dispatch to the right paint.Painter call sequence.

All shapes carry Style and Transform via Common fields; the renderer applies those before emitting geometry.

type Style

type Style struct {
	Fill          *Color // nil = inherit; (*Color)(nil) value with .None=true means fill="none"
	Stroke        *Color
	StrokeWidth   *float64
	Opacity       *float64
	FillOpacity   *float64
	StrokeOpacity *float64
	FillRule      FillRule // 0 = inherit; explicit values follow
}

Style is the resolved presentation attributes for a shape. nil-valued pointer fields mean "inherit from parent group" — the renderer's state stack walks the parent chain to fill them in. A non-nil value is what the SVG actually specified.

type Transform

type Transform struct {
	Ops []TransformOp
}

Transform is a small composite of the canonical SVG transform operations. Each entry in Ops applies in left-to-right order, which matches SVG's "transform=translate(10) rotate(45)" semantics.

func (Transform) IsIdentity

func (t Transform) IsIdentity() bool

IsIdentity reports whether no transform is set.

type TransformKind

type TransformKind int

TransformKind enumerates the supported transform operations.

const (
	TransformTranslate TransformKind = iota + 1
	TransformScale
	TransformRotate
	TransformMatrix
)

type TransformOp

type TransformOp struct {
	Kind TransformKind
	// Translate / Scale: X, Y
	// Rotate: X = angle deg; Y, A, B = optional center (cx, cy) when Has=true
	// Matrix: A..F as in SVG (a b c d e f)
	X, Y, A, B float64
	C, D, E, F float64
	Has        bool
}

TransformOp is one step of a Transform — the union over the SVG transform functions. Only one Kind is set per op.

type ViewBox

type ViewBox struct {
	X, Y, W, H float64
}

ViewBox is the SVG viewBox attribute, parsed into separate fields. Zero (all zero) means "no viewBox set".

func (ViewBox) Empty

func (v ViewBox) Empty() bool

Empty reports whether the viewBox is the zero value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL