本文延續 GD 库教學系列,重點講解 任意多邊形繪製(imagepolygon/imagefilledpolygon) 以及 基本文字輸出(imagestring/imagestringup) 技巧,為後續圖表、驗證碼開發奠基。
以陣列定義頂點座標(x1,y1,x2,y2...),imagepolygon() 自動閉合:
$parray = array(40,10, 60,10, 70,20, 60,50, 40,50, 30,20); // 6 點座標
imagepolygon($im, $parray, 6, $col_grn); // 畫六邊形輪廓
填充版本同理:
imagefilledpolygon($im, $parray, 6, $col_grn); // 實心六邊形
GD 內建 5 種內建字體(1~5,由小到大):
$str = "This is a test.";
for ($font = 1; $font <= 5; $font++) {
$y = 10 + ($font - 1) * 40; // 避免重疊
imagestring($im, $font, 10, $y, $str, $col_orn); // 水平文字
}
垂直文字使用 imagestringup(),參數用法相同:
for ($font = 1; $font <= 5; $font++) {
$x = 10 + ($font - 1) * 30;
imagestringup($im, $font, $x, 180, $str, $col_orn); // 垂直文字
}
imagettftext() 搭配 TrueType 字體檔(.ttf)。Header("Content-type: image/png"),結束時呼叫 imagedestroy() 釋放資源。| 圖形 | 必要參數 |
|---|---|
| 點 | x, y |
| 線 | x1, y1, x2, y2 |
| 矩形 | 左上 (x1,y1)、右下 (x2,y2) |
| 圓/橢圓/弧 | 中心 (cx,cy)、X半徑、Y半徑、起始角、結束角 |
| 多邊形 | 頂點座標陣列、頂點數 |
下一篇將介紹 TrueType 字體中文繪製與進階圖表應用。