我正在使用C#程序,我一直试图将一个点(x,y)旋转到任何程度,但我找不到更好的解决方案,我得到了这个功能:
private Point RotateCoordinates(int degrees, double x, double y)
{
Point coordinate = new Point();
if (degrees == 0 || degrees == 360)
{
coordinate.X = x;
coordinate.Y = y;
}
else if (degrees == 90)
{
coordinate.X = y.SetNegativeValues();
coordinate.Y = x;
}
else if (degrees == 180)
{
coordinate.X = x.SetNegativeValues();
coordinate.Y = y.SetNegativeValues();
}
else if (degrees == 270)
{
coordinate.X = y;
coordinate.Y = x.SetNegativeValues();
}
return coordinate;
}
正如您所看到的,此功能适用于90度,180度和270度。但问题是当我必须旋转55度,80度或其他任何程度。 有谁可以告诉我如何实施任何轮换?
答案 0 :(得分:1)
如果您想知道确切的数学,那么您应该搜索2D旋转矩阵示例。但是,你并不需要知道数学,因为.Net框架中内置了简单的旋转。
首先,如果您还没有WindowsBase程序集,请添加对WindowsBase程序集的引用。要执行2D旋转,您需要System.Windows.Vector和System.Windows.Media.Matrix。
示例:
using System.Windows;
using System.Windows.Media;
...
var originalPoint = new Vector(10, 0);
var transform = Matrix.Identity;
transform.Rotate(45.0); // 45 degree rotation
var rotatedPoint = originalPoint * transform;
2D旋转的数学实际上非常简单,因此使用两种新的对象类型可能看起来有点过分。但Matrix转换的优势在于,如果需要,可以将多个转换组合成单个矩阵。
答案 1 :(得分:1)
已经接受了答案,但如果你想在没有外部库的情况下这样做:
/// <summary>
/// Rotates the specified point around another center.
/// </summary>
/// <param name="center">Center point to rotate around.</param>
/// <param name="pt">Point to rotate.</param>
/// <param name="degree">Rotation degree. A value between 1 to 360.</param>
public static Point RotatePoint(Point center, Point pt, float degree)
{
double x1, x2, y1, y2;
x1 = center.X;
y1 = center.Y;
x2 = pt.X;
y2 = pt.Y;
double distance = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
degree *= (float)(Math.PI / 180);
double x3, y3;
x3 = distance * Math.Cos(degree) + x1;
y3 = distance * Math.Sin(degree) + y1;
return new Point((int)x3, (int)y3);
}
从汇编导入 Point
结构:System.Drawing
;所以,如果你不想引用它,你可以把它写下来:
public struct Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}