我已经搜索了所有关于矩形旋转的链接,但似乎没有任何内容适用于我的问题。我有一个 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);
我怎样才能做到这一点?
我不想在屏幕或其他任何东西上绘制这个矩形。我只需要这些值,但我读过的所有示例都使用图形类进行转换和绘制,这不是我想要的。
非常感谢
最佳答案
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
然后可以根据您要求的各种事情转换这些点,围绕一个点的旋转就是其中之一。其他包括缩放、剪切和翻译..
结果如预期:
如果您反复需要这个,您将需要创建函数将 Rectangle 转换为 Point[] 并返回。
注意,如上所述,后者是不可能的,因为Rectangle
总是正交的,即不能旋转 ,所以你将不得不去角点。或者从 System.Windows
命名空间切换到 Rect
类,如 Quergo 在他的帖子中所示。
关于c# - 如何使用矩阵旋转矩形并获得修改后的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885758/