当前位置: 首页> 最新文章列表> 如何在使用 imagestringup() 函数时,利用 imagefontwidth() 调整文本布局和对齐方式?

如何在使用 imagestringup() 函数时,利用 imagefontwidth() 调整文本布局和对齐方式?

M66 2025-06-15

在 PHP 中,imagestringup() 函数用于在图像上垂直方向绘制字符串。它与 imagestring() 类似,但绘制的文本是垂直向上的,这在生成带有旋转文本效果的图像时非常实用。然而,直接使用 imagestringup() 绘制文本时,文本的布局和对齐往往需要开发者手动控制,这时 imagefontwidth() 函数可以派上用场,帮助我们精确计算字符宽度,从而更好地调整文本的布局和对齐。

基本概念介绍

  • imagestringup()
    用于在图像上垂直绘制字符串,语法如下:

    bool imagestringup(resource $image, int $font, int $x, int $y, string $string, int $color);
    

    其中,$font 是内置字体大小(1~5),$x, $y 是起始坐标,$string 是文本内容,$color 是颜色资源。

  • imagefontwidth()
    返回指定内置字体大小的字符宽度,语法如下:

    int imagefontwidth(int $font);
    

结合使用这两个函数,可以控制文本绘制时的位置,避免文字重叠或布局不整齐。

为什么需要用 imagefontwidth() 调整文本布局?

由于 imagestringup() 是垂直绘制文本,每个字符的水平间距是固定的,但如果不计算字符宽度,直接给出坐标绘制,文本可能偏离预期位置,尤其是在绘制多行或需要居中对齐时。因此,需要先通过 imagefontwidth() 得到字体的字符宽度,计算每个字符的绘制位置,确保文本布局合理。

实际示例:实现垂直文本的水平居中对齐

假设我们希望在宽度为 200 像素的图像中,垂直绘制一行字符串,并实现水平居中对齐:

<?php
// 创建一个空白图像
$width = 200;
$height = 100;
$image = imagecreatetruecolor($width, $height);

// 分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// 填充背景色
imagefill($image, 0, 0, $white);

$text = "Hello";
$font = 5;  // 内置字体大小 1~5

// 计算文本宽度
$fontWidth = imagefontwidth($font);
$textWidth = strlen($text) * $fontWidth;

// 计算起始 x 坐标,实现水平居中
$x = ($width - $textWidth) / 2;

// y 坐标从底部开始向上绘制
$y = 80;

// 使用 imagestringup() 绘制垂直文本
imagestringup($image, $font, $x, $y, $text, $black);

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

说明:

  • 通过 imagefontwidth($font) 获得字体每个字符的宽度。

  • 乘以字符串长度得到整体文本宽度。

  • 用图像宽度减去文本宽度,再除以 2,实现文本水平居中。

  • imagestringup() 的坐标中,x 是文本左边缘,y 是文本底部基线的纵坐标。

进阶:实现多行垂直文本的居中对齐

如果需要绘制多行垂直文本,比如绘制多段文本从左到右排列,每段文本垂直显示,我们也可以利用 imagefontwidth() 计算每段文本宽度,动态调整 x 坐标:

<?php
$width = 300;
$height = 150;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $white);

$font = 4;
$texts = ["PHP", "Imagestringup", "Example"];

// 计算总宽度
$fontWidth = imagefontwidth($font);
$totalWidth = 0;
foreach ($texts as $t) {
    $totalWidth += strlen($t) * $fontWidth + 10; // 每段间隔10像素
}
$totalWidth -= 10; // 最后一个不加间隔

// 起始 x 坐标居中
$x = ($width - $totalWidth) / 2;
$y = 130;

foreach ($texts as $t) {
    imagestringup($image, $font, $x, $y, $t, $black);
    $x += strlen($t) * $fontWidth + 10;
}

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

这样可以灵活地控制多段垂直文本的排列和对齐。