旋转矩形的点位置
本文关键字:位置 旋转 | 更新日期: 2023-09-27 18:20:52
我有一个要旋转的矩形。
我只有矩形的一个点(鼠标位置),矩形的长度和宽度以及旋转的角度。现在我需要矩形的其他三个角的位置,这样我就可以很容易地用Graphics.DrawPolygon().绘制矩形
我不知道,因为我已经好几年没有数学了,需要你的帮助:D
我从互联网上尝试了很多解决方案,但都不适合我的问题。
下面的类执行您想要的操作。为了参考,请查看旋转是如何工作的:http://en.wikipedia.org/wiki/Rotation_matrix
public class MyRectangle
{
public double Length { get; set; }
public double Width { get; set; }
public double Rotation { get; private set; }
public Coord Center { get; private set; }
public Coord TopLeft { get; private set; }
public Coord TopRight { get; private set; }
public Coord BottomLeft { get; private set; }
public Coord BottomRight { get; private set; }
public MyRectangle(Coord origin, double length, double width)
{
Length = length;
Width = width;
Center = origin;
BottomLeft = new Coord(Center.X - Width / 2, Center.Y - Length / 2);
BottomRight = new Coord(Center.X + Width / 2, Center.Y - Length / 2);
TopLeft = new Coord(Center.X - Width / 2, Center.Y + Length / 2);
TopRight = new Coord(Center.X + Width / 2, Center.Y + Length / 2);
}
private void Move(Coord c)
{
InitCorners(new Coord((c.X - Center.X), (c.Y - Center.Y)));
Center.X = Center.X + (c.X - Center.X);
Center.Y = Center.Y + (c.Y - Center.Y);
}
private void InitCorners(Coord c)
{
BottomRight.X = (BottomRight.X + c.X );
BottomRight.Y = (BottomRight.Y + c.Y);
BottomLeft.X = (BottomLeft.X + c.X);
BottomLeft.Y = (BottomLeft.Y + c.Y);
TopRight.X = (TopRight.X + c.X);
TopRight.Y = (TopRight.Y + c.Y);
TopLeft.X = (TopLeft.X + c.X);
TopLeft.Y = (TopLeft.Y + c.Y);
}
public void Rotate(double qtyRadians)
{
//Move center to origin
Coord temp_orig = new Coord(Center.X, Center.Y);
Move(new Coord(0, 0));
BottomRight = RotatePoint(BottomRight, qtyRadians);
TopRight = RotatePoint(TopRight, qtyRadians);
BottomLeft = RotatePoint(BottomLeft, qtyRadians);
TopLeft = RotatePoint(TopLeft, qtyRadians);
//Move center back
Move(temp_orig);
}
Coord RotatePoint(Coord p, double qtyRadians)
{
Coord temb_br = new Coord(p.X, p.Y);
p.X = temb_br.X * Math.Cos(qtyRadians) - temb_br.Y * Math.Sin(qtyRadians);
p.Y = temb_br.Y * Math.Cos(qtyRadians) + temb_br.X * Math.Sin(qtyRadians);
return p;
}
}
[DebuggerDisplay("({X},{Y})")]
public class Coord
{
public double X { get; set; }
public double Y { get; set; }
public Coord(double x, double y)
{
X = x;
Y = y;
}
}