Last active
June 5, 2018 03:53
-
-
Save jackwillis/bcf2601f38743af844db9b6e277f4890 to your computer and use it in GitHub Desktop.
Measuring a font's x-height/cap-height ratio using rusttype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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