當前位置: 首頁> 最新文章列表> 動態生成坐標數組繪製任意邊數的多邊形

動態生成坐標數組繪製任意邊數的多邊形

M66 2025-05-29

在圖像處理領域,使用PHP的GD庫繪製圖形是一項常見的技能。其中, imageopenpolygon函數(正確函數名應為imagepolygon )可以用來繪製任意邊數的多邊形。本文將詳細介紹,如何動態生成坐標數組,並用它來繪製規則的N邊形。

一、什麼是imagepolygon?

imagepolygon()是PHP GD庫中用來繪製多邊形的函數。
它的基本用法如下:

 bool imagepolygon(
    GdImage $image,
    array $points,
    int $num_points,
    int $color
)
  • $image是圖像資源;

  • $points是點數組,格式如[x1, y1, x2, y2, ..., xn, yn]

  • $num_points是點的數量(不是數組元素數量,要除以2);

  • $color是繪製的顏色。

二、如何動態生成坐標數組?

要繪製任意邊數的多邊形(比如五邊形、八邊形等),我們可以用簡單的三角函數來生成坐標。思路如下:

  • 設定多邊形中心點(cx, cy)

  • 設定半徑r (即從中心到頂點的距離);

  • 均勻地在360°上分佈每個頂點;

  • 每個頂點的坐標可以通過正弦( sin ) 和余弦( cos ) 計算得到。

公式為:

 x = cx + r * cos(角度)
y = cy + r * sin(角度)

注意,PHP的cos()sin()接收的角度是弧度,需要用deg2rad()進行轉換。

三、完整PHP示例

下面是一個完整示例,演示如何動態生成坐標並繪製一個任意邊數的多邊形:

 <?php
// 設置圖片尺寸
$width = 400;
$height = 400;

// 創建畫布
$image = imagecreatetruecolor($width, $height);

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

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

// 多邊形參數
$number_of_sides = 7; // 例如,繪製七邊形
$radius = 150; // 半徑
$centerX = $width / 2;
$centerY = $height / 2;

// 生成坐標點
$points = [];
for ($i = 0; $i < $number_of_sides; $i++) {
    $angle_deg = (360 / $number_of_sides) * $i - 90; // 從頂部開始繪製
    $angle_rad = deg2rad($angle_deg);
    $x = $centerX + $radius * cos($angle_rad);
    $y = $centerY + $radius * sin($angle_rad);
    $points[] = (int)$x;
    $points[] = (int)$y;
}

// 繪製多邊形
imagepolygon($image, $points, $number_of_sides, $black);

// 輸出圖片到瀏覽器
header('Content-Type: image/png');
imagepng($image);

// 銷毀資源
imagedestroy($image);
?>

將上述代碼保存為PHP文件(如polygon.php ),通過瀏覽器訪問,即可看到一個規則的七邊形。

四、示例說明

  • 通過調整$number_of_sides變量,可以繪製不同邊數的多邊形;

  • $radius決定了多邊形的大小;

  • 角度的偏移量(這裡是-90度)使得第一個頂點在頂部,效果更美觀;

  • 如果需要把圖片保存到服務器,可以使用imagepng($image, 'path/to/file.png')

比如,保存圖片到m66.net/uploads/polygon.png

 imagepng($image, '/var/www/m66.net/uploads/polygon.png');

注意確保保存目錄有寫入權限!

五、總結

使用PHP的imagepolygon函數結合簡單的三角函數運算,我們可以輕鬆地繪製任意邊數的規則多邊形。這在製作圖形生成器、驗證碼、圖表組件時都有很大的用處。未來如果想繪製帶顏色填充的多邊形,還可以結合imagefilledpolygon()函數實現。