无法使用GD2水平居中“m”

时间:2014-03-06 07:57:14

标签: php image gd centering

我的目标是绘制一个水平居中的m。因此,我计算字母的宽度,从总宽度中减去该值,最后除以2.结果应该是左边的距离(或右边的距离)。

然而,'m'总是放错地方。我还注意到某些字体可能无法触发有问题的行为。请注意,我的脚本正确适用于所有其他拉丁字符。

Arial字体:

Misplaced 'm'; font: Arial

Bitstream Vera Sans:

Misplaced 'm'; font: 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);

1 个答案:

答案 0 :(得分:2)

每个字母留下一个小空格,每个字母都不同。 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);