首页 > 解决方案 > 在c#中以90/180/270旋转图像后找到新坐标

问题描述

我在 XML 文件中有一个图像(w:10,h:15)和一些图纸(一个矩形 A(6,4),W:2,H:4)。我需要在 C# 中将图像旋转 90/180/270 度后找出 A 的新坐标(即:A'(11,6))。

原始图像

90度旋转后

我尝试了以下代码,但我得到了相对于原始图像的 A'。我需要旋转图像中的 A' 坐标。

public static PointF RotatePoint(double x, double y, double pageHeight, double pageWidth, int rotateAngle)
    {
        //Calculate rotate angle in radian
        var angle = rotateAngle * Math.PI / 180.0f;

        //Find rotate orgin
        double rotateOrginX = pageWidth / 2;
        double rotateOrginY = pageHeight / 2;

        var cosA = Math.Cos(angle);
        var sinA = Math.Sin(angle);

        var pX = (float)(cosA * (x - rotateOrginX) - sinA * (y - rotateOrginY) + rotateOrginX);
        var pY = (float)(sinA * (x - rotateOrginX) + cosA * (y - rotateOrginY) + rotateOrginY);

        Console.WriteLine($"Rotate {rotateAngle}\tX: {pX}\tY: {pY}");

        return new PointF { X = pX, Y = pY };
    }

标签: c#graphicsrotationgeometry

解决方案


如果旋转仅是 90°、180° 或 270°,则使用Math.Sin()andCos()是过大的。

在 90° 旋转时,坐标可以很容易地操作......

W  : Image width before rotation
H  : Image height before rotation
x  : X coordinate in image before rotation
x' : X coordinate in image after rotation
y  : Y coordinate in image before rotation
y' : Y coordinate in image after rotation

For 0° CCW:
x' = x
y' = y

For 90° CCW:
x' = y
y' = W - x

For 180° CCW/CW:
x' = W - x
y' = H - y

For 270° CCW:
x' = H - y
y' = x

在 C# 中:

public static PointF RotatePoint(float x, float y, int pageWidth, int pageHeight, int degrees)
{
    switch(degrees)
    {
        case 0: return new PointF(x,y);
        case 90: return new PointF(y, pageWidth - x);
        case 180: return new PointF(pageWidth - x, pageHeight - y);
        case 270: return new PointF(pageHeight - y, x);
        default:
            // Either throw ArgumentException or implement the universal logic with Sin(), Cos()
    }
}

推荐阅读