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

3
我已经搜索了所有关于矩形旋转的链接,但没有找到适合我的问题的方法。我有一个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);

我该如何实现这个?

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

非常感谢

2个回答

4

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然后可以根据您要求的各种事物来转换这些点,包括绕点旋转。其他包括缩放剪切平移

预期的结果:

enter image description here

如果您需要重复此操作,则需要创建将矩形转换为点[]并返回的函数。

请注意,如上所述,后者实际上不可能,因为Rectangle将始终是直角的,即无法旋转,因此您将不得不选择角点。 或者切换到Quergo在他的帖子中展示的System.Windows命名空间中的Rect类。


0
如果您可以/想要使用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);

仍然是正交矩形: transformed = {-164.142,-15.858,200,200} - r2d2
transformed = {X,Y,宽度,高度} 对正交性没有提供任何信息。请检查左上角和右下角的角点。旋转不会改变宽度和高度。 - Quergo
1
OP 要求旋转角点。TaW 的被采纳的答案是正确的解决方案。 当我测试 original.Transform(m) 时,它会改变宽度和高度。它将修改原始值为 {-70.711,20,141.421,141.421}。它将保持垂直于坐标系,其中 TopLeft.Y = TopRight.Y。我猜这是 OP 预期的变换矩形的周围矩形。 - r2d2
你是对的。将代码示例更改为角点转换。这似乎可以完成工作。 - Quergo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接