在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);
結合使用這兩個函數,可以控製文本繪製時的位置,避免文字重疊或佈局不整齊。
由於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);
?>
這樣可以靈活地控制多段垂直文本的排列和對齊。