我在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 };
}
如果使用Math.Sin()
和Cos()
时旋转仅为90°、180°或270°,则会过度。
在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()
}
}