学习使用php实现根据不同字体大小对应的文字宽度、高度实现所在位置居中
imagettfbbox函数
<?php
$font_size = 70;//字体大小size
$angle = 0;//旋转角度
$ttf = 'fonts/siyuansongti-CN-Medium.otf';//字体文件,可以是url
$str = '农历六月初十';
$f = imagettfbbox($font_size, $angle, $ttf, $str);
echo "<pre>";
print_r($f);
/*解释
imagettfbbox() 返回一个含有 8 个单元的数组表示了文本外框的四个角:
0 左下角 X 位置
1 左下角 Y 位置
2 右下角 X 位置
3 右下角 Y 位置
4 右上角 X 位置
5 右上角 Y 位置
6 左上角 X 位置
7 左上角 Y 位置
*/
//获取字符串宽度可以 右下角 X 位置 - 左下角 X 位置
echo $fontwidth = $f[2] - $f[0];
echo "<br>";
//获取字符串高度可以 左下角 Y 位置 - 左上角 Y 位置
echo $fontwidth = $f[1] - $f[7];
echo "<br>";
?>
<p style="font-size:<?php echo $font_size ?>;font-family:<?php echo $ttf ?>">
<?php echo $str ?>
</p>
计算文字居中
//参数说明:字体大小,旋转角度,字体路径,文字
$fontBox = imagettfbbox($v[2], 0, $font, $this->to_entities($text));//文字水平居中实质
//得到文字的宽度
$font_width = bcsub($fontBox[2], $fontBox[0]);
//总宽度减去文字宽度
//居中
$x = ceil((bcsub($width, $font_width)) / 2);
如果不用to_entities方法会报错
imagettftext: any2eucjp: invalid code in input string