GD文字生成图片自动居中方法实现代码 [复制链接]

moqu8 2019-2-11

2481 0
662175c614e533ee2b.png

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)
}
也就相当于下面这样,返回了这一串字体的四个点的坐标:


460315c614e9636a0b.png

于是最后得到将字体居中的准确的算法:
$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);




最新回复 (0)
返回
支持中心
邮箱:winkill2012@qqcom
新站优化中!部分功能尚未完善,敬请谅解!
支持中心