如何使用矩阵旋转矩形并获得修改后的矩形?

How can I rotate a rectangle using a matrix and get the modified rectangle?

我已经搜索了所有关于矩形旋转的链接,但似乎没有任何内容适用于我的问题。我有一个 RectangleF 结构,希望将其输入旋转矩阵。然后使用生成的 RectangleF 传递给其他函数。

想要使用矩阵的原因是因为我可能还想执行平移,然后可能是缩放并将生成的矩形传递给其他函数,例如

RectangleF original = new RectangleF(0,0, 100, 100);
Matrix m = new Matrix();
m.Rotate(35.0f);
m.Translate(10, 20);

....   (what do I do here ?)

RectangleF modified = (How/where do I get the result?)

SomeOtherFunction(modified);

我怎样才能做到这一点?

我不想在屏幕上或其他任何地方绘制这个矩形。我只需要这些值,但我读过的所有示例都使用图形 class 进行转换和绘制,这不是我想要的。

非常感谢

System.Drawing.Rectangle结构总是正交的,不能有旋转。你只能旋转它的角点。

这是一个使用 Matrix:

执行此操作的示例
Matrix M = new Matrix();

// just a rectangle for testing..
Rectangle R = panel1.ClientRectangle;
R.Inflate(-33,-33);

// create an array of all corner points:
var p = new PointF[] {
    R.Location,
    new PointF(R.Right, R.Top),
    new PointF(R.Right, R.Bottom),
    new PointF(R.Left, R.Bottom) };

// rotate by 15° around the center point:
M.RotateAt(15, new PointF(R.X + R.Width / 2, R.Top + R.Height / 2));
M.TransformPoints(p);

// just a quick (and dirty!) test:
using (Graphics g = panel1.CreateGraphics())
{
    g.DrawRectangle(Pens.LightBlue, R);
    g.DrawPolygon(Pens.DarkGoldenrod, p );
}

诀窍是创建一个 PointPointF 的数组,其中包含您感兴趣的所有点,这里是四个角;然后 Matrix 可以根据您要求的各种事情转换这些点, 旋转 围绕一个点就是其中之一。其他包括缩放剪切平移..

结果如预期:

如果您反复需要这个,您将需要创建将 Rectangle 转换为 Point[] 并返回的函数。

注意,正如上面指出的那样,后者是不可能的,因为Rectangle总是正交的,即不能旋转,所以你将不得不去角点。或者从 System.Windows 命名空间切换到 Rect class,如 Quergo 在他的 post.

中所示

如果 can/want 使用 System.Windows 命名空间,请使用 Rect。 Rect 也始终是正交的,但您可以对其角点应用旋转变换。它与使用 System.Drawing 命名空间的过程相同。

var rect = new Rect(0, 0, 100, 100);
Point[] cornerPoints = { rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft };

var m = new Matrix();

//define rotation around rect center
m.RotateAt(45.0, rect.X + rect.Width / 2.0, rect.Y + rect.Height / 2.0);

//transform corner points
m.Transform(cornerPoints);