3 * Class with Font related methods.
6 declare(strict_types
=1);
11 use function is_array
;
12 use function mb_strlen
;
13 use function mb_strtolower
;
14 use function preg_replace
;
15 use function str_replace
;
18 * Class with Font related methods.
23 * Get list with characters and the corresponding width modifiers.
25 * @return (float|string[])[][] with characters and corresponding width modifier
27 public function getCharLists(): array
31 ['chars' => ['i', 'j', 'l'], 'modifier' => 0.23],
33 ['chars' => ['f'], 'modifier' => 0.27],
35 ['chars' => ['t', 'I'], 'modifier' => 0.28],
37 ['chars' => ['r'], 'modifier' => 0.34],
39 ['chars' => ['1'], 'modifier' => 0.49],
41 ['chars' => ['c', 'k', 's', 'v', 'x', 'y', 'z', 'J'], 'modifier' => 0.5],
42 //abdeghnopquL023456789
70 ['chars' => ['F', 'T', 'Z'], 'modifier' => 0.61],
72 ['chars' => ['A', 'B', 'E', 'K', 'P', 'S', 'V', 'X', 'Y'], 'modifier' => 0.67],
74 ['chars' => ['w', 'C', 'D', 'H', 'N', 'R', 'U'], 'modifier' => 0.73],
76 ['chars' => ['G', 'O', 'Q'], 'modifier' => 0.78],
78 ['chars' => ['m', 'M'], 'modifier' => 0.84],
80 ['chars' => ['W'], 'modifier' => 0.95],
82 ['chars' => [' '], 'modifier' => 0.28],
87 * Get width of string/text
89 * The text element width is calculated depending on font name
92 * @param string $text string of which the width will be calculated
93 * @param string $font name of the font like Arial,sans-serif etc
94 * @param int $fontSize size of font
95 * @param mixed[]|null $charLists list of characters and their width modifiers
97 * @return int width of the text
99 public function getStringWidth(
103 array|
null $charLists = null,
106 ! isset($charLists[0]['chars'], $charLists[0]['modifier'])
107 ||
! is_array($charLists[0]['chars'])
109 $charLists = $this->getCharLists();
112 // Start by counting the width, giving each character a modifying value
115 foreach ($charLists as $charList) {
116 $count +
= (mb_strlen($text)
117 - mb_strlen(str_replace($charList['chars'], '', $text))
118 ) * $charList['modifier'];
121 $text = str_replace(' ', '', $text);//remove the " "'s
123 $count +
= mb_strlen((string) preg_replace('/[a-z0-9]/i', '', $text)) * 0.3;
126 $font = mb_strtolower($font);
130 // no modifier for arial and sans-serif
134 case 'brushscriptstd':
135 case 'californian fb':
136 // .92 modifier for time, serif, brushscriptstd, and californian fb
140 // 1.23 modifier for broadway
145 $textWidth = $count * $fontSize;
147 return (int) ceil($textWidth * $modifier);