先通过多方向绘制轮廓文字再叠加主文字实现描边效果。使用PHP-GD的imagettftext在不同偏移位置画黑色文字形成轮廓,最后在原位画白色主文字,结合透明背景和合适字体路径完成带描边的文字图像。

PHP-GD 给文字添加描边效果,可以通过多次调用 imagettftext() 函数实现。GD 库本身没有直接的“描边”功能,但我们可以利用在不同偏移位置绘制颜色不同的文字来模拟描边效果。
先在多个方向(上下左右、四角)绘制一圈轮廓色的文字,再在中心绘制主文字,从而形成描边。
1. 创建画布并加载字体
确保服务器已安装 php-gd 扩展,并准备好一个 .ttf 字体文件。
2. 分别绘制描边和主体文字
使用两层绘制:
以下是一个完整的例子:
<?php
// 创建图像
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);
// 背景透明(可选)
$bg = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $bg);
// 定义颜色(描边为黑色,文字为白色)
$strokeColor = imagecolorallocate($image, 0, 0, 0); // 描边色
$mainColor   = imagecolorallocate($image, 255, 255, 255); // 主文字色
// 字体文件路径(必须是服务器上的绝对路径)
$fontFile = 'arial.ttf'; // 替换为你服务器上的 .ttf 文件路径
$text = 'Hello World';
// 文字起始坐标
$x = 50;
$y = 60;
// 字体大小
$fontSize = 40;
// 描边宽度(像素)
$strokeWidth = 2;
// 在多个方向绘制描边
for ($i = -$strokeWidth; $i <= $strokeWidth; $i++) {
    for ($j = -$strokeWidth; $j <= $strokeWidth; $j++) {
        if ($i != 0 || $j != 0) { // 不重复绘制中心点
            imagettftext($image, $fontSize, 0, $x + $i, $y + $j, $strokeColor, $fontFile, $text);
        }
    }
}
// 中心绘制主文字
imagettftext($image, $fontSize, 0, $x, $y, $mainColor, $fontFile, $text);
// 输出图像
header('Content-Type: image/png');
imagepng($image);
// 释放资源
imagedestroy($image);
?>
• 字体路径:确保 $fontFile 指向有效的 TTF 文件,相对路径容易出错,建议使用绝对路径。
• 透明背景:若需要透明背景,记得启用 alpha 支持(如上例)。
• 性能优化:描边宽度越大,绘制次数越多((2n+1)²),建议描边宽度设为 1~3 像素。
• 中文支持:使用支持中文的字体文件(如 simhei.ttf、msyh.ttf 等)。
以上就是php-gd如何设置文字描边_php-gd给文字添加描边效果的详细内容,更多请关注php中文网其它相关文章!
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号