圓餅圖 是資料視覺化中最直觀的圖表類型之一,適合展示各類別佔總體的比例關係。PHP GD 庫雖無內建圖表函數,但透過 imagefilledarc() 繪製填滿扇形,即可輕松實現動態圓餅圖生成。本文將從數據處理、角度計算、顏色分配到完整輸出,逐步講解實作細節。
圓餅圖本質上是多個**扇形** 首尾相連組成的圓形。關鍵在於根據數值比例計算每個扇形的**起始角度**與**結束角度**。
<?php
// 1. 準備數據:城市人口分布 (單位:萬)
$data = [
'北京' => 1925,
'上海' => 2016,
'廣州' => 1256,
'深圳' => 980
];
// 2. 建立真彩色畫布 (寬 400, 高 300)
$imgWidth = 400;
$imgHeight = 300;
$im = imagecreatetruecolor($imgWidth, $imgHeight);
// 3. 分配背景色 (白色) 並填滿
$bgColor = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bgColor);
// 4. 動態生成區分度高的隨機顏色
$colors = [];
$count = count($data);
// 為避免顏色過淺難以辨識,限制 RGB 最小值
for ($i = 0; $i < $count; $i++) {
$colors[] = imagecolorallocate($im, rand(50, 200), rand(50, 200), rand(50, 200));
}
// 5. 圓餅圖幾何參數
$centerX = $imgWidth / 2; // 圓心 X: 200
$centerY = $imgHeight / 2; // 圓心 Y: 150
$diameter = min($imgWidth, $imgHeight) * 0.8; // 直徑 240 (留白邊距)
$startAngle = 0; // 起始角度 (0度在 3 點鐘方向)
$total = array_sum($data); // 總人口 6177
// 6. 繪製扇形迴圈
foreach ($data as $index => $value) {
$endAngle = $startAngle + ($value / $total) * 360;
// imagefilledarc 參數說明:
// $im, $cx, $cy, $width, $height, $start, $end, $color, IMG_ARC_PIE
imagefilledarc(
$im,
$centerX, $centerY,
$diameter, $diameter, // 寬高相同為正圓
$startAngle, $endAngle,
$colors[$index],
IMG_ARC_PIE // 關鍵常數:繪製填滿扇形 (含圓心連線)
);
$startAngle = $endAngle; // 更新下一扇形起始角度
}
// 7. (進階) 添加圖例與標籤 - 此處省略,可使用 imagettftext 繪製
// 8. 輸出圖片
header('Content-Type: image/png');
imagepng($im);
// 9. 釋放記憶體
imagedestroy($im);
?>
bool imagefilledarc (
resource $image,
int $cx, int $cy, // 圓心座標
int $width, int $height, // 橢圓寬高 (相同為正圓)
int $start, int $end, // 起始/結束角度 (度數,順時針)
int $color, // 顏色識別碼
int $style // 模式常數
);
模式常數 ($style) 差異:
| 常數 | 效果 |
|---|---|
IMG_ARC_PIE | 繪製**實心扇形**,邊界包含兩條半徑連線至圓心 (標準圓餅圖) |
IMG_ARC_CHORD | 繪製**弦形**,邊界為弧線與弦 (直線連接兩端點,不連圓心) |
IMG_ARC_NOFILL | 僅繪製**輪廓線** (空心) |
IMG_ARC_EDGED | 連接圓心與弧線端點,**不填滿顏色** (僅畫邊框) |
可使用位元運算組合,如 IMG_ARC_PIE | IMG_ARC_NOFILL 畫出空心扇形邊框。
隨機色每次重新生成顏色不同,不利於品牌一致性或前端快取。建議預定義專業調色盤:
$palette = [
0x3498db, 0xe74c3c, 0x2ecc71, 0xf39c12,
0x9b59b6, 0x1abc9c, 0xe67e22, 0x34495e
];
$colors = [];
foreach ($palette as $hex) {
$r = ($hex >> 16) & 0xFF;
$g = ($hex >> 8) & 0xFF;
$b = $hex & 0xFF;
$colors[] = imagecolorallocate($im, $r, $g, $b);
}
GD 2.x 版本支援 imageantialias($im, true),但對 imagefilledarc 效果有限。生產環境建議:
imagescale() 縮小輸出。使用 imagettftext() 在扇形中央或外側繪製百分比文字,需計算扇形角平分線方向的座標:
$midAngle = deg2rad($startAngle + ($endAngle - $startAngle) / 2);
$labelX = $centerX + cos($midAngle) * ($diameter / 2 * 0.7);
$labelY = $centerY + sin($midAngle) * ($diameter / 2 * 0.7);
// 繪製百分比文字...
PHP GD 繪製圓餅圖的核心在於 數據歸一化 → 角度累加 → imagefilledarc 繪製 的流程。掌握 IMG_ARC_PIE 模式與角度計算邏輯,即可根據任意數據動態生成圓餅圖。對於商業級應用,建議考慮 pChart、PHPChart、或前端 Chart.js/ECharts 等更成熟的圖表庫,以獲得互動、動畫、響應式等豐富功能。