現在の位置: ホーム> 最新記事一覧> ImageOpenPolygon()回転変換による描画方向を変更する方法

ImageOpenPolygon()回転変換による描画方向を変更する方法

M66 2025-05-29

PHPでGDライブラリを使用してグラフィックを描画する場合、 ImageOpenPolygon()関数を使用して、オープンポリゴン(つまり、最後に接続されていないポリリン)を描画できます。デフォルトでは、 ImageOpenPolygon()は、提供するドットセットに基づいて直接描画されます。特定の角度で回転するなど、ポリゴンの描画方向を調整する場合は、座標ポイントを回転させる必要があります。

この記事では、PHPのImageOpenPolygon()によって描かれたグラフに回転変換を適用する方法を詳細に説明します。

回転変換の原理を理解します

2次元平面では、原点の周りに角度θを回転させた後(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で回転変換を適用します

上記の式に基づいてポイントのセットを回転させるために、小さな関数を記述できます。画像を作成し、回転したポリゴンを描画し、結果を出力する方法の完全な例を以下に示します。

 <?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]の1次元配列であることが必要です。

  • 回転するときは、図の中心を回転中心として使用して、図がキャンバスの中心から逸脱しないようにすることをお勧めします。

  • PHPの組み込みの三角関数はラジアンの単位にあるため、 deg2rad()は角度をラジアンに変換するために使用されます。

結論

単純な回転変換処理により、 ImageOpenPolygon()によって描かれた図を任意の角度で回転させることができます。これは非常に柔軟です。 PHP画像処理のヒントについて詳しく知りたい場合は、こちらの詳細なチュートリアルを参照できます。

この記事が、PHPでのImageOpenPolygon()と回転変換の組み合わせをよりよく理解できることを願っています!