use kurbo::BezPath;
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::prelude::{FontRef, LocationRef, MetadataProvider, Size};
pub struct GlyphOutline;
impl GlyphOutline {
#[must_use]
pub fn outline(
font_data: &[u8],
font_index: u32,
glyph_id: u32,
font_size: f32,
) -> Option<BezPath> {
let font = FontRef::from_index(font_data, font_index).ok()?;
let outline = font.outline_glyphs().get(skrifa::GlyphId::new(glyph_id))?;
let mut pen = BezPathPen::default();
outline
.draw(
DrawSettings::unhinted(Size::new(font_size), LocationRef::default()),
&mut pen,
)
.ok()?;
Some(pen.path)
}
}
#[derive(Default)]
struct BezPathPen {
path: BezPath,
}
impl OutlinePen for BezPathPen {
fn move_to(&mut self, x: f32, y: f32) {
self.path.move_to((x as f64, -y as f64));
}
fn line_to(&mut self, x: f32, y: f32) {
self.path.line_to((x as f64, -y as f64));
}
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
self.path
.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64));
}
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
self.path.curve_to(
(cx0 as f64, -cy0 as f64),
(cx1 as f64, -cy1 as f64),
(x as f64, -y as f64),
);
}
fn close(&mut self) {
self.path.close_path();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Color;
use crate::text::{RichSpan, TextStyle, layout_text};
use kurbo::Shape;
#[test]
fn outline_extracts_glyph_path() {
let style = TextStyle::new(Color::BLACK, 40.0, "sans-serif");
let layout = layout_text(std::slice::from_ref(&RichSpan::new("A", style)), None);
let run = &layout.lines[0].runs[0];
let glyph = &run.glyphs[0];
let path = GlyphOutline::outline(&run.font_data, run.font_index, glyph.id, run.font_size)
.expect("sans-serif 的 'A' 应有矢量轮廓");
assert!(
path.elements().len() >= 2,
"轮廓路径应至少含 move_to + 至少一个线段,got {} elements",
path.elements().len()
);
let bbox = path.bounding_box();
assert!(
bbox.width() > 0.0 || bbox.height() > 0.0,
"轮廓应有非零包围盒"
);
}
#[test]
fn outline_handles_invalid_input() {
assert!(GlyphOutline::outline(&[0u8; 8], 0, 0, 12.0).is_none());
let style = TextStyle::new(Color::BLACK, 40.0, "sans-serif");
let layout = layout_text(std::slice::from_ref(&RichSpan::new("A", style)), None);
let run = &layout.lines[0].runs[0];
assert!(
GlyphOutline::outline(&run.font_data, 99, run.glyphs[0].id, run.font_size).is_none(),
"单字体文件的越界集合索引应返回 None"
);
}
}