在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() ,配合字體文件實現更靈活的文字渲染。