使用imagettftext()函数可实现PHP中GD库绘制旋转文本,通过$angle参数设置旋转角度,以指定坐标为基线原点进行旋转,结合imagettfbbox()可优化定位,确保字体文件存在并支持所需字符集。

在PHP中使用GD库绘制旋转文本,可以通过 imagettftext() 函数实现。这个函数支持TrueType字体,并允许设置文字的旋转角度。
imagettftext() 是 GD 库中用于绘制带字体和旋转效果文本的核心函数。其语法如下:
array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
其中,$angle 参数就是控制文字旋转角度的(单位为度,顺时针为正,逆时针为负)。
文字的旋转是以指定坐标点 ($x, $y) 为原点进行的。注意:这个点是基线位置,不是文字中心,因此旋转后可能看起来偏移。
立即学习“PHP免费学习笔记(深入)”;
以下是一个完整示例,展示如何创建图像并绘制竖直方向的文字:
// 创建画布
$im = imagecreatetruecolor(200, 100);
// 分配颜色
$bg = imagecolorallocate($im, 255, 255, 255); // 白色背景
$textColor = imagecolorallocate($im, 0, 0, 0); // 黑色文字
// 填充背景
imagefilledrectangle($im, 0, 0, 199, 99, $bg);
// 设置字体文件路径(确保字体存在)
$fontFile = 'arial.ttf'; // 或使用系统字体路径如 '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
// 绘制90度旋转的文字(从下往上)
imagettftext($im, 16, 90, 50, 50, $textColor, $fontFile, 'Hello GD');
// 输出图像
header('Content-Type: image/png');
imagepng($im);
// 释放资源
imagedestroy($im);
实际使用中,旋转文本常因基线定位导致位置不准。可通过以下方式优化:
以上就是php-gd怎样设置文字角度_php-gd旋转文本角度方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号