【问题标题】:How can I rotate a rectangle using a matrix and get the modified rectangle?如何使用矩阵旋转矩形并获得修改后的矩形?
【发布时间】:2018-09-27 20:56:14
【问题描述】:

我已经搜索了矩形旋转的所有链接,但似乎没有任何问题适用于我的问题。我有一个 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);

我怎样才能做到这一点?

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

非常感谢

【问题讨论】:

    标签: c# matrix rotation


    【解决方案1】:

    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 );
    }
    

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

    结果如预期:

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

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

    【讨论】:

      【解决方案2】:

      如果您可以/想要使用 System.Windows 命名空间,请使用 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}
      • transformed = {X, Y, Width, Height} 没有提供有关正交性的信息。改为检查角点 TopLeft 和 BottomRight。宽度和高度不会因旋转而改变。
      • OP 要求旋转角点。 TaW 的公认答案是正确的解决方案。正如我测试的那样,original.Transform(m) 会改变宽度和高度。它将原始修改为{-70.711,20,141.421,141.421}。它将与坐标系保持正交,TopLeft.Y = TopRight.Y。我猜这是 OP 预期的转换矩形的周围矩形。
      • 你是对的。将代码示例更改为角点的转换。这似乎可以完成工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多