Skip to content

Instantly share code, notes, and snippets.

@dhardy
Created June 9, 2021 10:22
Show Gist options
  • Save dhardy/60ef7de0e291e54ef7b4e2f8b95e1819 to your computer and use it in GitHub Desktop.
Save dhardy/60ef7de0e291e54ef7b4e2f8b95e1819 to your computer and use it in GitHub Desktop.
Get glyph outline
[package]
name = "ttf-query"
version = "0.1.0"
edition = "2018"
[dependencies]
ab_glyph = "0.2.11"
fontdue = "0.5.2"
ttf-parser = "0.12.1"
use std::io::Read;
use std::fs::File;
use ttf_parser::{Face, OutlineBuilder};
// use ab_glyph::{Font, FontRef};
use fontdue::{Font, FontSettings};
struct VoidOutliner;
impl OutlineBuilder for VoidOutliner {
fn move_to(&mut self, x: f32, y: f32) {
eprintln!("outline-move_to({}, {})", x, y);
}
fn line_to(&mut self, x: f32, y: f32) {
eprintln!("outline-line_to({}, {})", x, y);
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
eprintln!("outline-quad_to({}, {}, {}, {})", x1, y1, x, y);
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
eprintln!(
"outline-curve_to({}, {}, {}, {}, {}, {})",
x1, y1, x2, y2, x, y
);
}
fn close(&mut self) {
eprintln!("outline-close");
}
}
fn main() {
let path = "/usr/share/fonts/google-carlito-fonts/Carlito-Regular.ttf";
let collection_index = 0;
let c = 'i';
let mut buf = Vec::new();
File::open(path).unwrap().read_to_end(&mut buf).unwrap();
// Test ttf-parser
let face = Face::from_slice(&buf, collection_index).unwrap();
let glyph = face.glyph_index(c).unwrap();
println!("ttf-parser index: {}", glyph.0);
match face.glyph_bounding_box(glyph) {
Some(rect) => println!("ttf-parser bounding box: {:?}", rect),
None => println!("ttf-parser failed to bound glyph"),
}
match face.outline_glyph(glyph, &mut VoidOutliner) {
Some(rect) => println!("ttf-parser outline bounding box: {:?}", rect),
None => println!("ttf-parser failed to outline glyph"),
}
// // Test ab_glyph
// let font = FontRef::try_from_slice_and_index(&buf, collection_index).unwrap();
//
// let glyph = font.glyph_id(c);
// println!("ab_glyph index: {}", glyph.0);
// match font.outline(glyph) {
// Some(o) => println!("ab_glyph bounding box: {:?}", o.bounds),
// None => println!("ab_glyph failed to bound glyph"),
// }
// Test fontdue
let scale = 40.0;
let font = Font::from_bytes(&buf[..], FontSettings {
collection_index,
scale,
}).unwrap();
let glyph = font.lookup_glyph_index(c);
println!("fontdue index: {}", glyph);
println!("fontdue metrics: {:?}", font.metrics(c, scale));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment