承接上篇,本文正式進入 GD 库繪圖核心,詳細解說 imageline()、imagedashedline() 以及 imagesetstyle() 實作虛線、彩色樣式線條的技巧,並驗證畫布座標系統的邊界特性。
Header("Content-type: image/png");
$im = imagecreate(200, 100); // 建立 200x100 畫布
$col_black = imagecolorallocate($im, 0, 0, 0);
$col_orn = imagecolorallocate($im, 255, 192, 0); // 橘色
$col_yel = imagecolorallocate($im, 255, 255, 0); // 黃色
畫布大小 200x100,有效座標範圍為 (0,0) 至 (199,99)。嘗試在 x=200 畫線將無輸出:
imageline($im, 0, 99, 199, 99, $col_yel); // 底部黃線:正常顯示
imageline($im, 200, 0, 200, 100, $col_orn); // 右邊界橘線:無輸出
PHP 4.0.6+ 支援 imagesetstyle() 定義顏色陣列,繪製交替色線條:
$col_red = imagecolorallocate($im, 255, 0, 0);
$style = array($col_red, $col_red, $col_black, $col_orn, $col_orn, $col_orn, $col_black);
imagesetstyle($im, $style);
imageline($im, 0, 50, 199, 50, IMG_COLOR_STYLED); // 紅-黑-橙循環樣式線
原理:$style 陣列順序決定像素著色循環,上例會產生「紅、紅、黑、橙、橙、橙、黑」週期性重複效果。
imagepng($im); // 輸出 PNG 影像
imagedestroy($im); // 釋放記憶體
| 函數 | 說明 | 支援版本 |
|---|---|---|
| imageline() | 實線 | 所有版本 |
| imagedashedline() | 虛線 | 所有版本 |
| imagesetstyle() + IMG_COLOR_STYLED | 自定義樣式線條 | PHP 4.0.6+ |
掌握線條繪製是進階幾何圖形(矩形、圓弧、多邊形)的基礎,下篇將介紹多邊形與文字繪製。