当前位置: 首页> 最新文章列表> 如何通过 imagefontwidth() 与 imagefilledrectangle() 函数在 PHP 中构建带背景的文字块?

如何通过 imagefontwidth() 与 imagefilledrectangle() 函数在 PHP 中构建带背景的文字块?

M66 2025-06-15

在 PHP 中,利用 GD 库进行图像处理是一种常见的操作。如果你想在图像上绘制带有背景色的文字块,imagefontwidth()imagefilledrectangle() 这两个函数将会非常有用。本文将详细介绍如何通过这两个函数实现带背景的文字块效果。

一、函数简介

  • imagefontwidth(int $font): int
    该函数返回指定内置字体的字符宽度。这里的 $font 是一个整数,代表 GD 库内置的字体大小(通常是 1~5)。知道字体的宽度后,我们可以计算文字块的宽度。

  • imagefilledrectangle(resource $image, int $x1, int $y1, int $x2, int $y2, int $color): bool
    该函数在图像 $image 上绘制一个填充的矩形,坐标为左上角 ($x1, $y1) 和右下角 ($x2, $y2),填充颜色为 $color

结合这两个函数,可以先根据文字长度和字体宽度计算背景矩形的大小,然后绘制矩形,最后绘制文字,从而形成带背景的文字块。

二、示例代码讲解

<?php
// 创建一个空白画布
$width = 300;
$height = 100;
$image = imagecreatetruecolor($width, $height);

// 设置颜色
$bgColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$textColor = imagecolorallocate($image, 0, 0, 0);     // 黑色文字
$rectColor = imagecolorallocate($image, 200, 200, 200); // 灰色背景块

// 填充画布背景色
imagefill($image, 0, 0, $bgColor);

// 文字和字体
$text = "PHP 带背景文字块示例";
$font = 5; // GD 内置字体大小,范围 1~5

// 计算文字宽高
$fontWidth = imagefontwidth($font);
$fontHeight = imagefontheight($font);
$textWidth = $fontWidth * strlen($text);
$textHeight = $fontHeight;

// 背景矩形坐标(留点边距)
$padding = 5;
$x1 = 50;
$y1 = 30;
$x2 = $x1 + $textWidth + 2 * $padding;
$y2 = $y1 + $textHeight + 2 * $padding;

// 绘制填充矩形作为背景
imagefilledrectangle($image, $x1, $y1, $x2, $y2, $rectColor);

// 在背景上绘制文字(注意偏移padding)
imagestring($image, $font, $x1 + $padding, $y1 + $padding, $text, $textColor);

// 输出图片
header('Content-Type: image/png');
imagepng($image);

// 释放资源
imagedestroy($image);
?>

代码要点

  • 使用 imagefontwidth($font)imagefontheight($font) 得到字体单个字符的宽度和高度。

  • 根据字符串长度计算整段文字的宽度。

  • 设置一个合适的内边距 $padding,让背景矩形不会紧贴文字。

  • imagefilledrectangle() 绘制背景矩形。

  • 再用 imagestring() 在背景矩形上绘制文字,确保文字有内边距。

三、扩展应用

  • 你可以通过调整 $rectColor 的颜色值,改变背景块的颜色。

  • 结合其他 GD 函数,还能实现更多效果,比如圆角矩形、阴影等。

  • 如果需要支持更复杂的字体样式,可以使用 imagettftext(),配合字体文件实现更灵活的文字渲染。

四、参考资料