Skip to content

Instantly share code, notes, and snippets.

@jackwillis
Last active June 5, 2018 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackwillis/bcf2601f38743af844db9b6e277f4890 to your computer and use it in GitHub Desktop.
Save jackwillis/bcf2601f38743af844db9b6e277f4890 to your computer and use it in GitHub Desktop.
Measuring a font's x-height/cap-height ratio using rusttype
extern crate num_rational; // 0.1
extern crate rusttype; // 0.6
use num_rational::Ratio;
use rusttype::{Font, FontCollection, Glyph, Rect};
fn main() {
let filename = "C:\\WINDOWS\\Fonts\\Tahoma.ttf";
let font = read_font_from_filename(filename);
let ratio = x_height_ratio(&font);
println!("x-height ratio: {} (~{:.3})",
ratio, ratio_into_f32(ratio).unwrap()
);
}
fn x_height_ratio(font: &Font) -> Ratio<i32> {
let x_height_glyphs = font.glyphs_for("vxz".chars());
let cap_height_glyphs = font.glyphs_for("HIT".chars());
let x_heights_sum = x_height_glyphs.map(glyph_height).sum::<i32>();
let cap_heights_sum = cap_height_glyphs.map(glyph_height).sum::<i32>();
Ratio::new(x_heights_sum, cap_heights_sum)
}
fn glyph_height(glyph: Glyph) -> i32 {
let glyph = glyph.standalone();
let extents: Rect<i32> = glyph
.get_data().unwrap()
.extents.unwrap();
extents.max.y - extents.min.y
}
fn read_font_from_filename(filename: &str) -> Font {
let data = std::fs::read(filename).unwrap();
FontCollection::from_bytes(data).unwrap()
.into_font().unwrap()
}
fn ratio_into_f32(ratio: Ratio<i32>) -> Option<f32> {
match ratio.denom() {
0 => None,
_ => Some(((*ratio.numer() as f64) / (*ratio.denom() as f64)) as f32)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment