繁体   English   中英

无法使用GD2将'm'水平居中

[英]Unable to horizontally center 'm' with GD2

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

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

宋体:

'm'放错位置;字体:Arial

位流Vera Sans:

'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);

每个字母剩下一个小空间,每个字母都不同。 PHP.net上的某人为此编写了一个解决方案: http : //www.php.net/manual/zh/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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM