將imagettftext()和imageline()結合使用,可應用於如下場景:
生成帶標註的折線圖
動態流程圖
驗證碼中的斜線乾擾與動態字體結合
圖形按鈕或結構圖中的文本標識
通過合適的坐標計算,我們可以使文本與圖形精準對齊,增強視覺效果。
以下示例展示瞭如何創建一張圖像,其中包含一條線段以及在線段起點和終點分別添加的文字說明。
<?php
// 創建畫布
$width = 400;
$height = 300;
$image = imagecreatetruecolor($width, $height);
// 顏色分配
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);
// 填充背景
imagefill($image, 0, 0, $white);
// 定義字體
$font = __DIR__ . '/arial.ttf'; // 確保arial.ttf字體文件存在
// 畫線
$x1 = 50; $y1 = 250;
$x2 = 350; $y2 = 50;
imageline($image, $x1, $y1, $x2, $y2, $blue);
// 添加文字(線起點)
imagettftext($image, 12, 0, $x1 - 30, $y1 + 20, $black, $font, '起點');
// 添加文字(線終點)
imagettftext($image, 12, 0, $x2 + 10, $y2, $black, $font, '終點');
// 輸出圖像
header('Content-Type: image/png');
imagepng($image);
// 銷毀資源
imagedestroy($image);
?>
該代碼創建了一張白色背景的圖像,在圖像上畫出一條藍色線段,並分別在起點和終點處添加註釋文字。 imagettftext()使得文字可以任意放置和旋轉, imageline()用於繪製圖形元素,兩者結合可以形成多樣化的信息圖。
通過在圖形中繪製標籤文字(例如超鏈接標題),可以實現更複雜的用途,如圖形站點地圖、流程提示等:
$url = 'https://gitbox.net/api/step?id=42';
$text = '查看詳情';
// 提取信息並繪製
imagettftext($image, 10, 0, 150, 100, $black, $font, $text);
雖然圖像不能直接點擊跳轉,但生成後的圖像可以作為網頁錨點的視覺提示配合HTML使用,提升用戶體驗。