c# - 在c#中以90/180/270旋转图像后找到新坐标
问题描述
我在 XML 文件中有一个图像(w:10,h:15)和一些图纸(一个矩形 A(6,4),W:2,H:4)。我需要在 C# 中将图像旋转 90/180/270 度后找出 A 的新坐标(即:A'(11,6))。
我尝试了以下代码,但我得到了相对于原始图像的 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 };
}
解决方案
如果旋转仅是 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()
}
}
推荐阅读
- javascript - 变量中的响应未正确显示
- javascript - 尝试在 vuejs 中获取我的本地 json 文件时未定义错误“要求”
- c++ - c ++使用char数组创建字符串
- arrays - 任务是编写一个程序,提示用户输入 2 个 2D 数组的大小,然后将它们相乘
- java - 身份核心迁移到 Java
- c++ - 使用类模板需要模板参数列表 c++ Visual Studios
- python - 代码显示类型错误必须是 str,而不是 int
- python - Error on Connect Selenium Driver to an Existing Chrome Browser Instance
- mysql - MySQL 前 10 天的普通价格与当前价格 - MySQL 性能改进
- math - 累积同质变换:旋转有效,但平移无效?