【问题标题】:Unable to horizontally center 'm' with GD2无法使用 GD2 水平居中“m”
【发布时间】:2026-01-03 22:50:02
【问题描述】:

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

但是,“m”总是放错了位置。我还注意到某些字体可能不会触发有问题的行为。请注意,我的脚本适用于所有其他拉丁字符。

宋体:

比特流 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);

【问题讨论】:

    标签: php image gd centering


    【解决方案1】:

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

    【讨论】:

    • 完美答案!非常感谢!我还设法将其垂直居中:$centeredY = (($totalHeight - $bbox['height']) / 2);$centeredY + $bbox['top'] 作为 imagettftext() 的 Y 参数。