在PHP中使用GD庫繪製圖形時, imageopenpolygon()函數可以用來繪製一個開放的多邊形(即首尾不相連的折線)。默認情況下, imageopenpolygon()是根據你提供的點集直接繪製的。如果你想調整多邊形的繪製方向,比如讓它旋轉一定的角度,就需要對坐標點進行旋轉變換處理。
本文將詳細講解如何在PHP中對imageopenpolygon()繪製的圖形應用旋轉變換。
在二維平面上,將一個點(x, y)繞原點(0, 0)旋轉角度θ 後,新坐標(x', y')計算公式是:
x' = x * cos(θ) - y * sin(θ)
y' = x * sin(θ) + y * cos(θ)
如果希望繞任意點(cx, cy)旋轉,需要先將坐標平移到原點,旋轉後再平移回來:
x' = cos(θ) * (x - cx) - sin(θ) * (y - cy) + cx
y' = sin(θ) * (x - cx) + cos(θ) * (y - cy) + cy
我們可以基於上面的公式,編寫一個小函數來旋轉一組點。以下是一個完整的示例,演示如何創建一個圖像、繪製旋轉後的多邊形,並輸出結果。
<?php
// 定義旋轉函數
function rotatePoints(array $points, float $angleDegrees, float $centerX = 0, float $centerY = 0): array {
$angleRadians = deg2rad($angleDegrees);
$cosTheta = cos($angleRadians);
$sinTheta = sin($angleRadians);
$rotatedPoints = [];
for ($i = 0; $i < count($points); $i += 2) {
$x = $points[$i];
$y = $points[$i + 1];
$xRotated = $cosTheta * ($x - $centerX) - $sinTheta * ($y - $centerY) + $centerX;
$yRotated = $sinTheta * ($x - $centerX) + $cosTheta * ($y - $centerY) + $centerY;
$rotatedPoints[] = $xRotated;
$rotatedPoints[] = $yRotated;
}
return $rotatedPoints;
}
// 創建畫布
$width = 400;
$height = 400;
$image = imagecreatetruecolor($width, $height);
// 分配顏色
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
$lineColor = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefill($image, 0, 0, $backgroundColor);
// 定義原始點集(一個簡單的三角形)
$points = [
200, 100, // 點1
300, 300, // 點2
100, 300 // 點3
];
// 設定旋轉角程度
$angle = 45; // 順時針旋轉45程度
// 计算旋轉后的點集
$rotatedPoints = rotatePoints($points, $angle, 200, 200); // 繞中心(200,200)旋轉
// 绘制旋轉后的开放多边形
imageopenpolygon($image, $rotatedPoints, count($rotatedPoints) / 2, $lineColor);
// 輸出圖像到瀏覽器
header('Content-Type: image/png');
imagepng($image);
// 銷毀資源
imagedestroy($image);
?>
imageopenpolygon()要求點數組是一維數組,順序是[x1, y1, x2, y2, ..., xn, yn] 。
旋轉時,最好以圖形中心為旋轉中心,這樣圖形不會偏離畫布中心。
PHP內置的三角函數以弧度製為單位,因此使用deg2rad()進行角度到弧度的轉換。
通過簡單的旋轉變換處理,我們可以讓imageopenpolygon()繪製出的圖形按照任意角度旋轉,非常靈活。如果你希望了解更多有關PHP圖像處理的技巧,可以參考這裡的詳細教程。
希望本文能幫你更好地掌握PHP中imageopenpolygon()與旋轉變換的結合使用!