在使用PHP處理圖像時, imagefttext函數是一個非常實用的工具,它允許我們在圖像上繪製支持TrueType 字體的文本。除了普通文字繪製,我們還可以為文字添加陰影效果,從而增強視覺層次感和美觀度。
本文將詳細講解如何使用imagefttext函數繪製帶陰影的文字,並通過實際代碼示例,幫助你快速掌握這一技巧。
首先,確保你的服務器環境已開啟GD 擴展,並且PHP 支持FreeType 字體庫。此外,你需要準備一個TTF 字體文件,例如常見的arial.ttf 。你可以從系統字體中復制,或下載喜歡的字體文件並存放於項目目錄中。
imagefttext的基本語法如下:
imagefttext(
GdImage $image,
float $size,
float $angle,
int $x,
int $y,
int $color,
string $font_filename,
string $text,
array $options = []
): array
在不添加陰影的情況下繪製文字,代碼可能如下所示:
$im = imagecreatetruecolor(400, 200);
$bg = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 400, 200, $bg);
$textColor = imagecolorallocate($im, 0, 0, 0);
$font = __DIR__ . '/arial.ttf';
imagefttext($im, 20, 0, 50, 100, $textColor, $font, 'Hello World');
繪製陰影的技巧是:先繪製陰影,再繪製主文字。通常陰影是略微偏移且顏色較深或透明度較低的同樣文字。
以下是添加陰影效果的完整示例:
$im = imagecreatetruecolor(400, 200);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 400, 200, $white);
// 陰影顏色(灰色)
$shadowColor = imagecolorallocate($im, 100, 100, 100);
// 主文字顏色(黑色)
$textColor = imagecolorallocate($im, 0, 0, 0);
$font = __DIR__ . '/arial.ttf';
$text = 'Hello Shadow';
// 文字位置與大小
$fontSize = 24;
$angle = 0;
$x = 50;
$y = 100;
// 先繪製陰影(向右下偏移2px)
imagefttext($im, $fontSize, $angle, $x + 2, $y + 2, $shadowColor, $font, $text);
// 再繪製主文字
imagefttext($im, $fontSize, $angle, $x, $y, $textColor, $font, $text);
// 輸出圖片
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
imagecolorallocate用於定義主文字和陰影的顏色。
陰影通過文字位置微調實現,例如(x+2, y+2) 。
陰影顏色應低於主文字顏色亮度,也可以通過imagecolorallocatealpha設置透明度以獲得更自然的陰影。
如果你想快速查看效果,可以將上述代碼保存為shadow-text.php文件並上傳到支持PHP 的服務器中,例如:
https://gitbox.net/shadow-text.php
確保服務器有對應的字體文件(如arial.ttf )在相同目錄下,否則會出現字體加載失敗的問題。
通過簡單的坐標偏移和合理配色,我們就可以用imagefttext實現令人滿意的文字陰影效果。這種技巧廣泛應用於驗證碼生成、水印繪製以及個性化圖像輸出中。善用GD 庫,可以大大提升你的圖像處理能力。
在今後的項目中,不妨多嘗試文字樣式的變化,比如疊加模糊陰影、多層投影、描邊效果等,進一步美化輸出圖像。