在一次项目中需要把一段文字放到画板的中间,经过一开始的计算(
fontSize*$fontCount)/2,得到的x轴坐标位置并不正确。查询资料得知,半角的西文部分是比例字体,全角字符是等宽字体;
中国的汉字就是等宽字体,但是有TrueType的存在,字体的宽度往往不能这样计算,这时候可能需要使用一个新的PHP函数计算字符串在画板上的起始位置;
PS:TrueType字体,实际上我们展示的是红框的位置,字体大小会有误差;
php引入了一个函数:
imagettfbbox() – 取得使用 TrueType 字体的文本的范围
返回结果:
array imagettfbbox ( float size, float angle, string fontfile, string text )
本函数计算并返回一个包围着 TrueType 文本范围的虚拟方框的像素大小,返回一个数组。
类似于这样:
array(8) {
[0]=> int(0)
[1]=> int(9)
[2]=> int(335)
[3]=> int(9)
[4]=> int(335)
[5]=> int(-56)
[6]=> int(0)
[7]=> int(-56)
}
也就相当于下面这样,返回了这一串字体的四个点的坐标:
{6,7} {4,5}
文字
{0,1} {2,3}
于是最后得到将字体居中的准确的算法:
$width = $height = 500;
$size = 50;
$file = './1.ttf';
$content = "你好啊世界";
$path = './1.png';
$a = imagettfbbox($size, 0, $file, $content); //得到字符串虚拟方框四个点的坐标
$len = $a[2] - $a[0];
$x = ($width-$len)/2;
$y = $a[3]-$a[5]
$dst = imagecreatetruecolor($width,$height);
$black = imagecolorallocate($dst, 0, 0, 0);
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst,0,0,$white);
imagettftext($dst,$size,0,$x,$y,$black, $file, $content);
imagepng($dst,$path);
imagedestroy($dst);