我的任务是绘制特定的图形。作为此任务的一部分,我需要将一些点旋转45度。
我已经花了2天的时间来计算公式,但无法正确完成。
我一直在到处搜寻这个网站,包括这个特定的网站,我已经很近了,但是我仍然不在那儿。
这里是:
我需要画四个不同的点
我有一个特定的公式来计算位置,这超出了问题的范围,但这是我从中得到的结果:
int radius = 576;
int diameter = radius * 2;
Point blueA = new Point(561, 273);
Point greenB = new Point(273, 561);
Point yellowC = new Point (849, 561);
Point redD = new Point (561, 849);
现在,我需要将这些点旋转45度。我使用以下代码来实现它:
double rotationAngle = 45;
double rotationRadians = rotationAngle * (Math.PI / 180);
int center = radius;
result.X = (int)(Math.Cos(rotationRadians) * ((double)result.X - (double)center) - (double)Math.Sin(rotationRadians) * ((double)result.Y - center) + (double)center);
result.Y = (int)(Math.Sin(rotationRadians) * ((double)result.X - (double)center) + (double)Math.Cos(rotationRadians) * ((double)result.Y - center) + (double)center);
但这就是我得到的:
任何帮助将非常感激
最佳答案
问题是您正在设置int center = radius
的int radius = 576
。这肯定没有意义,因为您确定要围绕应该具有x和y位置的点旋转。
假设您绕原点旋转,则中心x
和y
都应为0
而非576
。
因此,鉴于此,请尝试此操作。
/// <summary>
/// Rotates one point around another
/// </summary>
/// <param name="pointToRotate">The point to rotate.</param>
/// <param name="centerPoint">The center point of rotation.</param>
/// <param name="angleInDegrees">The rotation angle in degrees.</param>
/// <returns>Rotated point</returns>
static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees)
{
double angleInRadians = angleInDegrees * (Math.PI / 180);
double cosTheta = Math.Cos(angleInRadians);
double sinTheta = Math.Sin(angleInRadians);
return new Point
{
X =
(int)
(cosTheta * (pointToRotate.X - centerPoint.X) -
sinTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.X),
Y =
(int)
(sinTheta * (pointToRotate.X - centerPoint.X) +
cosTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.Y)
};
}
像这样使用。
Point center = new Point(0, 0);
Point newPoint = RotatePoint(blueA, center, 45);
显然,如果中心点始终为
0,0
,则可以相应地简化函数,或者通过默认参数或重载方法使中心点为可选。您可能还希望将一些可重用的数学封装到其他静态方法中。例如
/// <summary>
/// Converts an angle in decimal degress to radians.
/// </summary>
/// <param name="angleInDegrees">The angle in degrees to convert.</param>
/// <returns>Angle in radians</returns>
static double DegreesToRadians(double angleInDegrees)
{
return angleInDegrees * (Math.PI / 180);
}
/// <summary>
/// Rotates a point around the origin
/// </summary>
/// <param name="pointToRotate">The point to rotate.</param>
/// <param name="angleInDegrees">The rotation angle in degrees.</param>
/// <returns>Rotated point</returns>
static Point RotatePoint(Point pointToRotate, double angleInDegrees)
{
return RotatePoint(pointToRotate, new Point(0, 0), angleInDegrees);
}
像这样使用。
Point newPoint = RotatePoint(blueA, 45);
最后,如果您使用的是GDI,还可以简单地执行
RotateTransform
。另请:http://msdn.microsoft.com/en-us/library/a0z3f662.aspx
Graphics g = this.CreateGraphics();
g.TranslateTransform(blueA);
g.RotateTransform(45);