Skip to main content

SvgRenderer

Struct SvgRenderer 

Source
pub struct SvgRenderer { /* private fields */ }
Expand description

SVG renderer: accumulates the SVG string.

Implementations§

Source§

impl SvgRenderer

Source

pub fn new(width: f64, height: f64) -> Self

Create a renderer for an output canvas of width × height (scene units / px).

A non-positive size means “unset”: the value from the rendered Scene is then used, so SvgRenderer::new(0.0, 0.0) still produces a correctly sized document.

Examples found in repository?
examples/sketch_demo.rs (line 139)
138fn render_svg(scene: &Scene) -> String {
139    let mut r = SvgRenderer::new(scene.width, scene.height).with_background(scene.background);
140    scene.render(&mut r);
141    r.into_string()
142}
More examples
Hide additional examples
examples/rot_text.rs (line 30)
10fn main() {
11    let mut scene = Scene::new(400.0, 300.0).with_background(Color::WHITE);
12
13    let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif")
14        .with_align(TextAlign::Left)
15        .with_baseline(TextBaseline::Top)
16        .with_rotation(45_f64.to_radians());
17
18    scene.push(Element::text(
19        "2026-10-01",
20        Point::new(50.0, 80.0),
21        style.clone(),
22    ));
23    scene.push(Element::text(
24        "不旋转的对照",
25        Point::new(50.0, 220.0),
26        style.with_rotation(0.0),
27    ));
28
29    // SVG
30    let mut r = SvgRenderer::new(400.0, 300.0);
31    r.render_scene(&scene);
32    std::fs::write("rot_text.svg", r.into_string()).unwrap();
33    println!("wrote rot_text.svg");
34
35    // PNG
36    let mut r = VelloPixmapRenderer::new(400, 300);
37    let pixmap = r.render_scene_to_pixmap(&scene);
38    std::fs::write("rot_text.png", pixmap.to_png()).unwrap();
39    println!("wrote rot_text.png");
40}
examples/demo.rs (line 281)
276fn main() {
277    let scene = build_scene();
278
279    // SVG 输出(render_scene 会自动捕获 scene 的 title/description/scale 与各图层)
280    // 两个后端同一契约:构造尺寸 = 输出尺寸,故这里显式乘 scale 得到 2× 画布。
281    let mut svg = SvgRenderer::new(scene.width * scene.scale, scene.height * scene.scale)
282        .with_background(scene.background);
283    scene.render(&mut svg);
284    let svg_str = svg.into_string();
285    std::fs::write("demo.svg", &svg_str).expect("写 SVG 失败");
286    println!("SVG 已写入 demo.svg ({} 字节)", svg_str.len());
287    println!("  图层数: {}", scene.layers().len());
288    for l in scene.layers() {
289        println!(
290            "  - {} ({} 节点, visible={})",
291            l.name,
292            l.nodes.len(),
293            l.visible
294        );
295    }
296    // 演示 measure_text / TextMetrics(canvas 风格)
297    let demo_style = lievisual::TextStyle::new(Color::BLACK, 20.0, "sans-serif");
298    let tm = lievisual::measure_text(
299        std::slice::from_ref(&lievisual::RichSpan::new(
300            "Measure 示例",
301            demo_style.clone(),
302        )),
303        None,
304    );
305    println!(
306        "  测量 \"Measure 示例\": width={:.2} height={:.2} alphabetic_baseline={:.2} ascent={:.2} descent={:.2}",
307        tm.metrics.width,
308        tm.metrics.height,
309        tm.metrics.alphabetic_baseline,
310        tm.metrics.font_bounding_box_ascent,
311        tm.metrics.font_bounding_box_descent
312    );
313
314    // PNG 输出
315    {
316        use lievisual::render::VelloPixmapRenderer;
317        // 与 SVG 端同一契约:构造尺寸 = 输出尺寸,乘 scale 提升栅格分辨率。
318        let mut renderer = VelloPixmapRenderer::new(
319            (scene.width * scene.scale) as u32,
320            (scene.height * scene.scale) as u32,
321        )
322        .with_background(scene.background);
323        let png = renderer.render_png(&scene);
324        std::fs::write("demo.png", &png).expect("写 PNG 失败");
325        println!("PNG 已写入 demo.png ({} 字节)", png.len());
326    }
327}
Source

pub fn with_background(self, bg: Color) -> Self

Explicit background color; when unset, Scene::background is used.

Examples found in repository?
examples/sketch_demo.rs (line 139)
138fn render_svg(scene: &Scene) -> String {
139    let mut r = SvgRenderer::new(scene.width, scene.height).with_background(scene.background);
140    scene.render(&mut r);
141    r.into_string()
142}
More examples
Hide additional examples
examples/demo.rs (line 282)
276fn main() {
277    let scene = build_scene();
278
279    // SVG 输出(render_scene 会自动捕获 scene 的 title/description/scale 与各图层)
280    // 两个后端同一契约:构造尺寸 = 输出尺寸,故这里显式乘 scale 得到 2× 画布。
281    let mut svg = SvgRenderer::new(scene.width * scene.scale, scene.height * scene.scale)
282        .with_background(scene.background);
283    scene.render(&mut svg);
284    let svg_str = svg.into_string();
285    std::fs::write("demo.svg", &svg_str).expect("写 SVG 失败");
286    println!("SVG 已写入 demo.svg ({} 字节)", svg_str.len());
287    println!("  图层数: {}", scene.layers().len());
288    for l in scene.layers() {
289        println!(
290            "  - {} ({} 节点, visible={})",
291            l.name,
292            l.nodes.len(),
293            l.visible
294        );
295    }
296    // 演示 measure_text / TextMetrics(canvas 风格)
297    let demo_style = lievisual::TextStyle::new(Color::BLACK, 20.0, "sans-serif");
298    let tm = lievisual::measure_text(
299        std::slice::from_ref(&lievisual::RichSpan::new(
300            "Measure 示例",
301            demo_style.clone(),
302        )),
303        None,
304    );
305    println!(
306        "  测量 \"Measure 示例\": width={:.2} height={:.2} alphabetic_baseline={:.2} ascent={:.2} descent={:.2}",
307        tm.metrics.width,
308        tm.metrics.height,
309        tm.metrics.alphabetic_baseline,
310        tm.metrics.font_bounding_box_ascent,
311        tm.metrics.font_bounding_box_descent
312    );
313
314    // PNG 输出
315    {
316        use lievisual::render::VelloPixmapRenderer;
317        // 与 SVG 端同一契约:构造尺寸 = 输出尺寸,乘 scale 提升栅格分辨率。
318        let mut renderer = VelloPixmapRenderer::new(
319            (scene.width * scene.scale) as u32,
320            (scene.height * scene.scale) as u32,
321        )
322        .with_background(scene.background);
323        let png = renderer.render_png(&scene);
324        std::fs::write("demo.png", &png).expect("写 PNG 失败");
325        println!("PNG 已写入 demo.png ({} 字节)", png.len());
326    }
327}
Source

pub fn with_scale(self, scale: f64) -> Self

Output scale (pixel density): enlarges width/height while keeping viewBox unchanged.

Takes precedence over Scene::scale; when unset, the scene’s scale is used.

Source

pub fn with_sizing(self, sizing: SvgSizing) -> Self

Root width / height strategy; see SvgSizing.

Source

pub fn with_style(self, style: impl Into<String>) -> Self

CSS appended to the root’s style attribute (XML-attribute escaped).

Used for things the backends cannot express: capping the rendered width (max-width: 130px), declaring a background-color, …

Source

pub fn with_title(self, title: impl Into<String>) -> Self

Document title.

Source

pub fn with_description(self, description: impl Into<String>) -> Self

Document description.

Source

pub fn into_string(self) -> String

Take the complete SVG document (including the <svg> root and background).

Sizing contract (same as the raster backend): the size given to SvgRenderer::new is the output size — it lands verbatim in the root width/height attributes, and viewBox is that size divided by scale:

width/height = 输出尺寸            (SvgRenderer::new 传入)
viewBox      = 0 0 (输出尺寸/scale) (绘制使用的用户坐标系)

scale is therefore a density knob, applied symmetrically on both backends, and it never silently enlarges the output. To export a scene at 2× density, pass new(w * 2.0, h * 2.0) (the new(0.0, 0.0) fallback does this for you, treating scene.width/scene.height as logical size).

That size only reaches the root width / height attributes under SvgSizing::Fixed; under SvgSizing::Intrinsic the viewport is left to the host CSS and only viewBox carries the geometry.

Examples found in repository?
examples/sketch_demo.rs (line 141)
138fn render_svg(scene: &Scene) -> String {
139    let mut r = SvgRenderer::new(scene.width, scene.height).with_background(scene.background);
140    scene.render(&mut r);
141    r.into_string()
142}
More examples
Hide additional examples
examples/rot_text.rs (line 32)
10fn main() {
11    let mut scene = Scene::new(400.0, 300.0).with_background(Color::WHITE);
12
13    let style = TextStyle::new(Color::BLACK, 20.0, "sans-serif")
14        .with_align(TextAlign::Left)
15        .with_baseline(TextBaseline::Top)
16        .with_rotation(45_f64.to_radians());
17
18    scene.push(Element::text(
19        "2026-10-01",
20        Point::new(50.0, 80.0),
21        style.clone(),
22    ));
23    scene.push(Element::text(
24        "不旋转的对照",
25        Point::new(50.0, 220.0),
26        style.with_rotation(0.0),
27    ));
28
29    // SVG
30    let mut r = SvgRenderer::new(400.0, 300.0);
31    r.render_scene(&scene);
32    std::fs::write("rot_text.svg", r.into_string()).unwrap();
33    println!("wrote rot_text.svg");
34
35    // PNG
36    let mut r = VelloPixmapRenderer::new(400, 300);
37    let pixmap = r.render_scene_to_pixmap(&scene);
38    std::fs::write("rot_text.png", pixmap.to_png()).unwrap();
39    println!("wrote rot_text.png");
40}
examples/demo.rs (line 284)
276fn main() {
277    let scene = build_scene();
278
279    // SVG 输出(render_scene 会自动捕获 scene 的 title/description/scale 与各图层)
280    // 两个后端同一契约:构造尺寸 = 输出尺寸,故这里显式乘 scale 得到 2× 画布。
281    let mut svg = SvgRenderer::new(scene.width * scene.scale, scene.height * scene.scale)
282        .with_background(scene.background);
283    scene.render(&mut svg);
284    let svg_str = svg.into_string();
285    std::fs::write("demo.svg", &svg_str).expect("写 SVG 失败");
286    println!("SVG 已写入 demo.svg ({} 字节)", svg_str.len());
287    println!("  图层数: {}", scene.layers().len());
288    for l in scene.layers() {
289        println!(
290            "  - {} ({} 节点, visible={})",
291            l.name,
292            l.nodes.len(),
293            l.visible
294        );
295    }
296    // 演示 measure_text / TextMetrics(canvas 风格)
297    let demo_style = lievisual::TextStyle::new(Color::BLACK, 20.0, "sans-serif");
298    let tm = lievisual::measure_text(
299        std::slice::from_ref(&lievisual::RichSpan::new(
300            "Measure 示例",
301            demo_style.clone(),
302        )),
303        None,
304    );
305    println!(
306        "  测量 \"Measure 示例\": width={:.2} height={:.2} alphabetic_baseline={:.2} ascent={:.2} descent={:.2}",
307        tm.metrics.width,
308        tm.metrics.height,
309        tm.metrics.alphabetic_baseline,
310        tm.metrics.font_bounding_box_ascent,
311        tm.metrics.font_bounding_box_descent
312    );
313
314    // PNG 输出
315    {
316        use lievisual::render::VelloPixmapRenderer;
317        // 与 SVG 端同一契约:构造尺寸 = 输出尺寸,乘 scale 提升栅格分辨率。
318        let mut renderer = VelloPixmapRenderer::new(
319            (scene.width * scene.scale) as u32,
320            (scene.height * scene.scale) as u32,
321        )
322        .with_background(scene.background);
323        let png = renderer.render_png(&scene);
324        std::fs::write("demo.png", &png).expect("写 PNG 失败");
325        println!("PNG 已写入 demo.png ({} 字节)", png.len());
326    }
327}

Trait Implementations§

Source§

impl Renderer for SvgRenderer

Source§

fn render_scene(&mut self, scene: &Scene)

Render the whole scene: the default implementation handles sorting and recursion. A backend may override this to capture Scene metadata (title / description / scale), then call Renderer::render_scene_ordered to reuse the default traversal.
Source§

fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle)

Draw an axis-aligned rectangle.
Source§

fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle)

Draw a circle.
Source§

fn draw_ellipse( &mut self, center: Point, radii: Vec2, rotation: f64, style: &FillStrokeStyle, )

Draw an ellipse (radii are the two semi-axis lengths, rotation is the angle around the center).
Source§

fn draw_rounded_rect( &mut self, rect: Rect, radius: f64, style: &FillStrokeStyle, )

Draw a rounded rectangle with a uniform corner radius.
Source§

fn draw_line(&mut self, start: Point, end: Point, style: &Stroke)

Draw a line segment.
Source§

fn draw_polyline(&mut self, points: &[Point], style: &Stroke)

Draw a polyline (multiple connected segments, open, stroke only).
Source§

fn draw_polygon(&mut self, points: &[Point], style: &FillStrokeStyle)

Draw a polygon (closed, filled + optional stroke).
Source§

fn draw_arc( &mut self, center: Point, radii: Vec2, start_angle: f64, sweep_angle: f64, style: &Stroke, )

Draw an arc (open, stroke only).
Source§

fn draw_pie( &mut self, center: Point, radius: f64, start_angle: f64, sweep_angle: f64, style: &FillStrokeStyle, )

Draw a pie sector (closed, including the two radius edges from the center to the arc endpoints, filled + optional stroke).
Source§

fn draw_path(&mut self, path: &BezPath, style: &FillStrokeStyle, closed: bool)

Draw a path (optionally closed for fill or stroke).
Source§

fn draw_gradient_path( &mut self, path: &BezPath, gradient: &LinearGradient, stroke: Option<&Stroke>, )

Draw a path with a linear-gradient fill.
Source§

fn draw_text( &mut self, spans: &[RichSpan], position: Point, style: &TextStyle, layout: Option<&TextLayout>, )

Draw text. The styled spans are the core content; when layout is provided it takes precedence. Read more
Source§

fn draw_image(&mut self, image: &SceneImage, frame: Rect, opacity: f64)

Draw an image: image is a self-contained RGBA8 bitmap and frame is the display rectangle (pt/px coordinates). Read more
Source§

fn push_transform(&mut self, t: Transform)

Enter a transform scope (for a Group or node-local transform). Empty by default; backends with stack-based state (vello / svg group) should override.
Source§

fn pop_transform(&mut self)

Exit the scope established by Renderer::push_transform.
Source§

fn push_opacity(&mut self, opacity: f64)

Enter an opacity scope (for a node / subtree with opacity < 1). Empty by default.
Source§

fn pop_opacity(&mut self)

Exit the scope established by Renderer::push_opacity.
Source§

fn push_blend(&mut self, mode: BlendMode)

Enter a blend-mode scope: everything drawn until Renderer::pop_blend is composited with the backdrop using mode. Empty by default (backends without blend support ignore it, degrading to BlendMode::Normal).
Source§

fn pop_blend(&mut self)

Exit the scope established by Renderer::push_blend.
Source§

fn push_mask(&mut self, mask: &Mask)

Enter a mask scope: everything drawn until Renderer::pop_mask has its composited alpha multiplied by mask. Empty by default (backends without mask support ignore it).
Source§

fn pop_mask(&mut self)

Exit the scope established by Renderer::push_mask.
Source§

fn push_filter(&mut self, filter: &Filter)

Enter a filter scope: everything drawn until Renderer::pop_filter is rendered into an offscreen layer and filtered (blur / drop shadow). Empty by default.
Source§

fn pop_filter(&mut self)

Exit the scope established by Renderer::push_filter.
Source§

fn push_name(&mut self, name: Option<&str>)

Enter a named scope (for a node with name; emits id on the SVG side). name is an Option: None means no id attribute is emitted.
Source§

fn pop_name(&mut self)

Exit the scope established by Renderer::push_name.
Source§

fn push_clip(&mut self, clip: &Clip)

Enter a clip scope (for a node / subtree with clip). Empty by default.
Source§

fn pop_clip(&mut self)

Exit the scope established by Renderer::push_clip.
Source§

fn push_color_matrix(&mut self, matrix: ColorMatrix)

Enter a colour-matrix scope: every paint colour emitted until Renderer::pop_color_matrix is transformed by matrix. Read more
Source§

fn pop_color_matrix(&mut self)

Exit the scope established by Renderer::push_color_matrix.
Source§

fn push_antialias(&mut self, enabled: bool)

Enter an anti-aliasing scope: shapes drawn until Renderer::pop_antialias use enabled anti-aliasing. Read more
Source§

fn pop_antialias(&mut self)

Exit the scope established by Renderer::push_antialias.
Source§

fn draw_rounded_rect_radii( &mut self, rect: Rect, radii: CornerRadii, style: &FillStrokeStyle, )

Draw a rounded rectangle with per-corner radii. Read more
Source§

fn push_scope(&mut self, scope: &NodeScope<'_>)

Enter a compositing scope: stacks transform, clip, filter, opacity, blend, mask and name, in exactly that order. Read more
Source§

fn pop_scope(&mut self, scope: &NodeScope<'_>)

Exit the scope established by Renderer::push_scope (pops in reverse order).
Source§

fn push_node_scope(&mut self, node: &SceneNode)

Enter the node-level scope (delegates to Renderer::push_scope).
Source§

fn pop_node_scope(&mut self, node: &SceneNode)

Exit the scope established by Renderer::push_node_scope.
Source§

fn render_children(&mut self, nodes: &[SceneNode])

Draw a slice of nodes in stable ascending z_index order. Read more
Source§

fn render_scene_ordered(&mut self, scene: &Scene)

Default traversal: draws the default nodes layer first (bottommost, sorted stably by ascending z_index), then each Layer in array order from bottom to top.
Source§

fn render_layer(&mut self, layer: &Layer)

Render a single layer: apply the layer-level scope, then render each node inside the layer stably by ascending z_index (including container recursion). Rarely needs to be overridden. Read more
Source§

fn render_node(&mut self, node: &SceneNode)

Render a single node: enter the node’s scope, draw its content (a leaf primitive, or a container’s children), then leave the scope. Rarely needs to be overridden.
Source§

fn draw_element(&mut self, element: &Element)

Draw one leaf primitive, dispatching to the atomic draw_* methods. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

Source§

fn simd_from(_simd: S, value: T) -> T

Source§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

Source§

fn simd_into(self, simd: S) -> T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.