drawlang-render 0.1.0

SVG/PNG/PDF backends for the drawlang DSL
Documentation
//! PNG rasterization of our own SVG via resvg, with the bundled fonts loaded
//! so text renders identically to how it was measured.

use drawlang_core::text::{FONT_BOLD, FONT_REGULAR};

pub fn render_png(svg: &str, scale: f32) -> Result<Vec<u8>, String> {
    let mut fontdb = resvg::usvg::fontdb::Database::new();
    fontdb.load_font_data(FONT_REGULAR.to_vec());
    fontdb.load_font_data(FONT_BOLD.to_vec());

    let options = resvg::usvg::Options {
        fontdb: std::sync::Arc::new(fontdb),
        ..Default::default()
    };
    let tree = resvg::usvg::Tree::from_str(svg, &options).map_err(|e| format!("svg parse: {e}"))?;

    let size = tree.size();
    let w = (size.width() * scale).ceil() as u32;
    let h = (size.height() * scale).ceil() as u32;
    let mut pixmap = resvg::tiny_skia::Pixmap::new(w.max(1), h.max(1))
        .ok_or_else(|| "pixmap allocation failed".to_string())?;

    resvg::render(
        &tree,
        resvg::tiny_skia::Transform::from_scale(scale, scale),
        &mut pixmap.as_mut(),
    );
    pixmap.encode_png().map_err(|e| format!("png encode: {e}"))
}