首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法用GD2水平居中“m”

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

Stack Overflow用户
提问于 2014-03-06 07:57:13
回答 1查看 43关注 0票数 1

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

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

阿里尔:

Bitstream Vera Sans:

代码语言:javascript
复制
<?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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-06 08:50:01

每个字母都有一个很小的空间,这是不同的。PHP.net上有人为此写了一个解决方案:http://www.php.net/manual/en/function.imagettfbbox.php#97357

你需要调整一下你的代码。

代码语言:javascript
复制
$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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22218400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档