常用填充函式
| 函式 | 參數 | 說明 |
imagefill | (img, x, y, color) | 從 (x,y) 起始漫水填充相鄰同色區域 |
imagefilledellipse | (img, cx, cy, w, h, color) | 以 (cx,cy) 為中心畫填充橢圓/圓 |
imagefilledrectangle | (img, x1, y1, x2, y2, color) | 畫填充矩形,左上 (x1,y1) 右下 (x2,y2) |
imagefilledarc | (img, cx, cy, w, h, s, e, color, style) | 畫填充橢圓弧/扇形,s/e 為起始/結束角度,style 可組合:
IMG_ARC_PIE 扇形、IMG_ARC_CHORD 弦、IMG_ARC_NOFILL 僅邊框、IMG_ARC_EDGED 連接中心 |
完整範例:藍底白圓與白方塊
<?php
header('Content-Type: image/png');
$img = imagecreate(400, 200);
$bg = imagecolorallocate($img, 0, 0, 255); // 藍底
$white = imagecolorallocate($img, 255, 255, 255);
imagefilledellipse($img, 100, 100, 150, 150, $white); // 圓心(100,100) 直徑150
imagefilledrectangle($img, 200, 50, 300, 150, $white); // 矩形
imagepng($img);
imagedestroy($img);

進階:繪製餅圖
$data = [30, 50, 20]; // 百分比
$colors = [
imagecolorallocate($img, 255, 0, 0),
imagecolorallocate($img, 0, 255, 0),
imagecolorallocate($img, 0, 0, 255),
];
$start = 0;
foreach ($data as $i => $percent) {
$end = $start + $percent * 3.6; // 360° 對應 100%
imagefilledarc($img, 200, 100, 150, 150, $start, $end, $colors[$i], IMG_ARC_PIE);
$start = $end;
}
注意事項
- 座標原點 (0,0) 在左上角,X 向右、Y 向下。
- 真彩色圖片請用
imagecreatetruecolor(),調色盤模式 imagecreate() 已過時。
- 輸出前務必發送正確
Content-Type 標頭。
- 釋放資源
imagedestroy() 避免記憶體洩漏。