Last active
May 12, 2025 10:34
-
-
Save szepeviktor/701b08582f4a0653822c0dfdda5215cd to your computer and use it in GitHub Desktop.
Estimate glyph widths for sans serif 16px font
This file contains hidden or 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
<?php | |
function get_text_width(string $text): int | |
{ | |
$glyph_widths = [ | |
'A' => 10.67, | |
'B' => 10.67, | |
'C' => 11.55, | |
'D' => 11.55, | |
'E' => 10.67, | |
'F' => 9.77, | |
'G' => 12.45, | |
'H' => 11.55, | |
'I' => 4.45, | |
'J' => 8.00, | |
'K' => 10.67, | |
'L' => 8.90, | |
'M' => 13.33, | |
'N' => 11.55, | |
'O' => 12.45, | |
'P' => 10.67, | |
'Q' => 12.45, | |
'R' => 11.55, | |
'S' => 10.67, | |
'T' => 9.77, | |
'U' => 11.55, | |
'V' => 10.67, | |
'W' => 15.10, | |
'X' => 10.67, | |
'Y' => 10.67, | |
'Z' => 9.77, | |
'a' => 7.10, | |
'b' => 8.00, | |
'c' => 7.10, | |
'd' => 8.00, | |
'e' => 7.10, | |
'f' => 5.33, | |
'g' => 8.00, | |
'h' => 8.00, | |
'i' => 4.45, | |
'j' => 4.45, | |
'k' => 8.00, | |
'l' => 4.45, | |
'm' => 12.45, | |
'n' => 8.00, | |
'o' => 8.00, | |
'p' => 8.00, | |
'q' => 8.00, | |
'r' => 5.33, | |
's' => 6.23, | |
't' => 4.45, | |
'u' => 8.00, | |
'v' => 8.00, | |
'w' => 11.55, | |
'x' => 8.00, | |
'y' => 8.00, | |
'z' => 7.10, | |
]; | |
$letters = preg_replace('/[^a-zA-Z]/', 'b', iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text)); | |
return (int) array_reduce(str_split($letters), static function ($width, $char) use ($glyph_widths) { | |
return $width + $glyph_widths[$char]; | |
}, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment