當前位置: 首頁> 最新文章列表> 如何使用imagefilledpolygon() 替代imageopenpolygon() 實現填充多邊形

如何使用imagefilledpolygon() 替代imageopenpolygon() 實現填充多邊形

M66 2025-05-29

在使用PHP 的GD 庫進行圖形繪製時,開發者有時需要在圖像上繪製多邊形。傳統上, imageopenpolygon()函數可以繪製一個空心的多邊形輪廓。但有些時候,我們希望使用imagefilledpolygon()來實現更加靈活的繪製效果,尤其是在需要處理顏色填充和輪廓樣式時。本文將介紹如何使用imagefilledpolygon()替代imageopenpolygon() ,並解決繪製空心多邊形的問題。

為什麼使用imagefilledpolygon()替代imageopenpolygon()

imageopenpolygon()主要用於繪製空心的多邊形,其效果僅僅是描邊,不進行內部填充。而imagefilledpolygon()則可以直接繪製一個填充的多邊形。

如果你想要繪製帶有特定邊框顏色或者更複雜控制的多邊形, imagefilledpolygon()的靈活性更高。尤其是當imageopenpolygon()不支持更多樣的繪製需求時,用imagefilledpolygon()自己模擬輪廓繪製會是一個不錯的替代方案。

使用方法

基本思路是:

  1. 使用imagefilledpolygon()繪製一個填充的多邊形(使用背景色或透明色填充)。

  2. 使用imageline()單獨繪製多邊形的邊框。

這樣可以手動控制填充色與邊框色,達到想要的空心多邊形效果。

示例代碼

下面是一個完整的示例,演示如何用imagefilledpolygon()實現類似imageopenpolygon()的效果。

 <?php
// 創建畫布
$image = imagecreatetruecolor(300, 300);

// 分配顏色
$white = imagecolorallocate($image, 255, 255, 255);
$borderColor = imagecolorallocate($image, 0, 0, 0);

// 填充背景
imagefill($image, 0, 0, $white);

// 定義多邊形的點
$points = [
    50, 50,
    250, 70,
    200, 200,
    100, 250,
    60, 150
];

// 填充多邊形(用背景色,保持內部透明或同色)
imagefilledpolygon($image, $points, count($points) / 2, $white);

// 繪製多邊形邊框
$num_points = count($points) / 2;
for ($i = 0; $i < $num_points; $i++) {
    $x1 = $points[$i * 2];
    $y1 = $points[$i * 2 + 1];
    $x2 = $points[(($i + 1) % $num_points) * 2];
    $y2 = $points[(($i + 1) % $num_points) * 2 + 1];
    imageline($image, $x1, $y1, $x2, $y2, $borderColor);
}

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

// 釋放資源
imagedestroy($image);
?>

代碼說明

  • imagefilledpolygon()用背景色填充,防止內部區域變色。

  • 使用循環的imageline()手動連接各個頂點,繪製多邊形的外邊框。

  • ($i + 1) % $num_points確保最後一個點能和第一個點連接閉合。

注意事項

擴展:在實際項目中的應用