當前位置: 首頁> 最新文章列表> 結合字符統計和imagefontwidth() 繪製文字柱狀圖

結合字符統計和imagefontwidth() 繪製文字柱狀圖

M66 2025-05-28

在Web 開發中,繪製圖表是一項常見的需求,尤其是在展示統計數據時。雖然有許多專業的圖表庫,但有時候我們只需要用簡單的文字和PHP 的內置函數來快速實現一個直觀的柱狀圖。本文將介紹如何結合字符統計和PHP 的imagefontwidth()函數,利用GD 庫繪製一個簡單的文字柱狀圖。

一、核心思路

柱狀圖的橫軸用文字表示類別,縱軸用文字字符表示數值的大小。我們通過統計字符串中字符的數量,結合imagefontwidth()函數計算單個字符寬度,從而動態繪製每個柱子的寬度。

二、準備工作

確保你的PHP 環境支持GD 庫,通常只需開啟php_gd2擴展即可。

三、關鍵函數介紹

  • imagefontwidth(int $font): int
    返回內置字體的字符寬度。 GD 庫內置了幾種字體(1 到5),大小和寬度各不相同。

  • imagestring(resource $image, int $font, int $x, int $y, string $string, int $color): bool
    在圖像中繪製字符串。

四、示例代碼

下面用一個簡單示例演示如何繪製文字柱狀圖:

 <?php
// 數據樣例,類別 => 數值(用字符長度表示)
$data = [
    '蘋果' => 5,
    '香蕉' => 8,
    '橘子' => 3,
    '葡萄' => 6,
    '梨子' => 4,
];

// 畫布大小
$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);

// 選擇字體大小(1 到 5)
$font = 5;
$fontWidth = imagefontwidth($font);
$fontHeight = imagefontheight($font);

// 計算柱子間距
$barSpacing = 10;

// 定義起始繪製坐標
$xStart = 50;
$yStart = 50;

// 最大柱子長度(字符數量映射為像素)
$maxLength = max($data);
$maxBarWidth = 200;

// 遍歷數據繪製柱狀圖
foreach ($data as $label => $value) {
    // 計算柱子寬度,基于最大數值缩放
    $barWidth = intval($value / $maxLength * $maxBarWidth);

    // 繪製柱子(用藍色矩形)
    imagefilledrectangle($image, $xStart, $yStart, $xStart + $barWidth, $yStart + $fontHeight, $blue);

    // 绘制類別文字(在柱子左側)
    imagestring($image, $font, $xStart - strlen($label) * $fontWidth - 10, $yStart, $label, $black);

    // 绘制數值文字(在柱子右側)
    imagestring($image, $font, $xStart + $barWidth + 5, $yStart, str_repeat('|', $value), $black);

    // 下一條柱子縱坐標下移
    $yStart += $fontHeight + $barSpacing;
}

// 輸出圖片頭部
header('Content-Type: image/png');
imagepng($image);

// 釋放內存
imagedestroy($image);
?>

五、代碼說明

  • $data數組定義了各類別及其對應的數值。數值越大,柱子越長。

  • 使用imagefontwidth()獲取字符寬度,保證文字和柱子長度計算精準。

  • imagefilledrectangle()繪製柱狀矩形。

  • imagestring()繪製類別名稱和用|字符表示的數值柱狀圖。

  • 動態計算柱子寬度,柱子長度與最大數值成比例。

六、效果展示

運行上述PHP 腳本後,會生成一張PNG 圖片,顯示簡單的文字柱狀圖,橫向排列的藍色柱子表示數值大小,左側是類別名稱,右側是用豎線字符表示的數值條。


此方法適合對圖形要求不高,或需要快速生成簡單統計圖的場景。結合更多GD 函數,也能繪製更複雜的圖形和圖表。

如果你想進一步優化,比如加坐標軸、標題、動態字體,可以在此基礎上擴展。