我的目标是画一个水平中心的m。因此,我计算字母的宽度,从总宽度减去这个值,最后除以2。结果应该是从左边的距离(或与右边的距离相等)。
然而,“m”总是错误的。我还注意到,有些字体可能不会触发问题行为。请注意,我的脚本正确地适用于所有其他拉丁字符。
阿里尔:

Bitstream Vera Sans:

<?php
$totalWidth = 100;
$totalHeight = 100;
$font = 'Arial.ttf';
$img = imagecreatetruecolor($totalWidth, $totalHeight);
$red = imagecolorallocate($img, 255, 0, 0);
$fontSize = 100;
$bbox = imagettfbbox($fontSize, 0, $font, 'm');
$width = max($bbox[2], $bbox[4]) - max($bbox[0], $bbox[6]);
$centeredX = ($totalWidth - $width) / 2;
imagettftext($img, 100, 0, $centeredX, 100, $red, $font, 'm');
imagepng($img, 'testcase.png');
imagedestroy($img);发布于 2014-03-06 08:50:01
每个字母都有一个很小的空间,这是不同的。PHP.net上有人为此写了一个解决方案:http://www.php.net/manual/en/function.imagettfbbox.php#97357
你需要调整一下你的代码。
$totalWidth = 100;
$totalHeight = 100;
$font = 'Arial.ttf';
// change letter to see it with different letters
$letter = "m";
$img = imagecreatetruecolor($totalWidth, $totalHeight);
$red = imagecolorallocate($img, 255, 0, 0);
$fontSize = 100;
$bbox = calculateTextBox($fontSize, 0, $font, $letter);
$centeredX = (($totalWidth - $bbox['width']) / 2);
// here left coordinate is subtracted (+ negative value) from centeredX
imagettftext($img, 100, 0, $centeredX + $bbox['left'], 100, $red, $font, $letter);
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);https://stackoverflow.com/questions/22218400
复制相似问题