当前位置: 首页> 最新文章列表> 如何使用 imagefontwidth() 判断文字宽度,避免文字在图片上超出边界?

如何使用 imagefontwidth() 判断文字宽度,避免文字在图片上超出边界?

M66 2025-07-10

在使用 PHP 生成带有文字的图片时,常常需要确保文字不会超出图片的边界,从而影响整体的美观和可读性。PHP 提供了多种函数来处理图片和文字,其中 imagefontwidth() 是一个非常实用的函数,它能帮助我们获取指定字体大小的单个字符的宽度,从而计算出整段文字的宽度。

本文将详细介绍如何使用 imagefontwidth() 判断文字宽度,并在绘制文字到图片时避免文字超出边界。

一、什么是 imagefontwidth()?

imagefontwidth() 函数的作用是返回某个内置字体字符的宽度,单位是像素。它的函数定义如下:

int imagefontwidth(int $font);

参数 $font 是字体大小,取值范围通常是 1 到 5,代表 PHP 内置的五种字体大小。

通过这个函数,我们可以得到每个字符的宽度,然后结合字符串长度,就能计算出整段文字的宽度。

二、判断文字宽度示例

下面的代码展示了如何计算字符串宽度并判断它是否超过指定图片宽度:

<?php
// 设定图片宽度
$image_width = 200;

// 选择字体大小,1 到 5
$font = 3;

// 要绘制的字符串
$text = "这是一个测试文字";

// 计算单个字符宽度
$char_width = imagefontwidth($font);

// 计算字符串宽度
$text_width = strlen($text) * $char_width;

// 判断文字是否超出边界
if ($text_width > $image_width) {
    echo "文字宽度超过图片宽度,可能会超出边界";
} else {
    echo "文字宽度在图片范围内,可以绘制";
}
?>

注意:上面代码中,strlen() 计算的是字节长度,如果文字是中文,建议使用 mb_strlen() 计算字符长度,以避免中文字符被错误计算:

$text_length = mb_strlen($text, 'UTF-8');
$text_width = $text_length * $char_width;

三、结合 imagefontwidth() 绘制文字并避免超出

当你要把文字写到图片上时,可以先测量文字宽度,再决定是否需要缩小字体、截断文字或者换行。以下示例展示如何根据图片宽度自动截断文字,避免超出:

<?php
// 创建空白图片
$image_width = 200;
$image_height = 50;
$image = imagecreatetruecolor($image_width, $image_height);

// 设置背景颜色
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);

// 设置字体颜色
$text_color = imagecolorallocate($image, 0, 0, 0);

// 文字内容
$text = "这是一个测试文字,可能会很长";

// 选择字体大小
$font = 3;
$char_width = imagefontwidth($font);

// 计算最多能显示多少字符
$max_chars = floor($image_width / $char_width);

// 截断文字,防止超出图片宽度
if (mb_strlen($text, 'UTF-8') > $max_chars) {
    $text = mb_substr($text, 0, $max_chars, 'UTF-8') . '...';
}

// 计算文字宽度,居中显示
$text_length = mb_strlen($text, 'UTF-8');
$text_width = $text_length * $char_width;
$x = ($image_width - $text_width) / 2;
$y = ($image_height - imagefontheight($font)) / 2;

// 绘制文字
imagestring($image, $font, $x, $y, $text, $text_color);

// 输出图片
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>

四、小结

  • 使用 imagefontwidth($font) 可以获得单个字符的宽度。

  • 结合 mb_strlen() 计算字符串的字符数,得到文字总宽度。

  • 比较文字宽度与图片宽度,判断是否会超出。

  • 根据情况截断文字或调整字体大小,确保文字在图片范围内。

  • 这种方法适合使用 PHP 内置字体绘制文字的场景。

如果你需要使用 TTF 字体绘制文字,推荐使用 imagettfbbox() 来更精确地测量文字尺寸。