在PHP 中, imageopenpolygon()函數用於在圖像上繪製一個多邊形。此函數的語法如下:
bool imageopenpolygon(resource $image, array $points, int $num_points, int $color)
$image :目標圖像資源,通常由imagecreate()或imagecreatefromjpeg()等函數創建。
$points :一個數組,包含多邊形的各個點的坐標。每個坐標由兩個整數值組成(x 和y)。
$num_points :多邊形的頂點數量。
$color :用於繪製多邊形的顏色,通常通過imagecolorallocate()或imagecolorallocatealpha()函數創建。
在imageopenpolygon()函數中, $color參數決定了多邊形的填充顏色。如果要設置顏色,你首先需要使用imagecolorallocate()函數來分配一個顏色值。這個函數的格式是:
int imagecolorallocate(resource $image, int $red, int $green, int $blue)
其中, $image是目標圖像資源, $red 、 $green和$blue分別是顏色的RGB 值,範圍是0 到255。通過這個函數,你可以設置不同的顏色。
<?php
// 創建一個 400x400 的圖像
$image = imagecreate(400, 400);
// 分配顏色
$bg_color = imagecolorallocate($image, 255, 255, 255); // 白色背景
$polygon_color = imagecolorallocate($image, 0, 0, 255); // 藍色多邊形
// 設置多邊形的頂點
$points = array(
100, 100, // 點 1 (x1, y1)
300, 100, // 點 2 (x2, y2)
350, 250, // 點 3 (x3, y3)
250, 350, // 點 4 (x4, y4)
150, 250 // 點 5 (x5, y5)
);
// 在圖像上繪製多邊形
imageopenpolygon($image, $points, count($points) / 2, $polygon_color);
// 輸出圖像
header('Content-Type: image/png');
imagepng($image);
// 銷毀圖像資源
imagedestroy($image);
?>
創建圖像資源:通過imagecreate()創建了一個400x400 像素的圖像。
分配顏色:使用imagecolorallocate()分別為背景和多邊形分配了顏色。背景是白色(RGB:255, 255, 255),多邊形是藍色(RGB:0, 0, 255)。
繪製多邊形:通過imageopenpolygon()函數,使用設定的頂點數組$points和顏色$polygon_color繪製了一個多邊形。
imageopenpolygon()函數並不會自動關閉圖像資源,因此需要使用imagedestroy()函數來銷毀圖像,釋放內存。
若要使用透明度效果,可以使用imagecolorallocatealpha()來創建帶有透明度的顏色。
通過以上方法,你可以輕鬆在圖像上繪製具有不同顏色的多邊形。