问题描述
我已经搜索了矩形旋转的所有链接,但似乎没有任何问题适用于我的问题.我有一个 RectangleF 结构并希望将其输入到旋转矩阵中.然后使用生成的 RectangleF 传递给其他函数.
I have searched all the links for rectangle rotation, but nothing seems to apply to my problem. I have a RectangleF structure and wish to feed it into a rotation matrix. Then use resulting RectangleF to pass into some other function.
想要使用矩阵的原因是因为我可能还想执行平移,然后可能是缩放,然后将生成的矩形传递给其他函数,例如
The reason for wanting to use a matrix is because I may also want to perform a translation, and then perhaps a scale afterwards and pass the resultant rectangle into some other function, e.g.
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);
我怎样才能做到这一点?
How can I achieve this ?
我不想在屏幕或其他任何东西上绘制这个矩形.我只需要这些值,但我读过的所有示例都使用图形类进行转换和绘制,这不是我想要的.
I don't want to draw this rectangle on a screen or anything else. I just need the values, but all examples I have read use the graphics class to do the transform and draw which is not what I want.
非常感谢
推荐答案
System.Drawing.Rectangle
结构总是正交的,不能有旋转.你只能旋转它的角点.
The System.Drawing.Rectangle
structure is always orthogonal and cannot have a rotation. You can only rotate its corner points.
这是一个使用 Matrix
执行此操作的示例:
Here is an example of doing this with a 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 就是其中之一.其他包括缩放、剪切和平移..
The trick is to create an array of Point
or PointF
containg all points you are interested in, here the four corners; the Matrix
can then transform those points according to all sorts of things you asked for, rotation around a point being one of them. Others include scaling, shearing and translating..
结果如预期:
如果您反复需要此功能,您将需要创建将 Rectangle 转换为 Point[] 并返回的函数.
If you need this repeatedly you will want to create function to convert Rectangle to Point[] and back.
注意,如上所述,后者实际上是不可能的,因为 Rectangle
总是正交的,即不能旋转,所以你将不得不去角点.或者从 System.Windows
命名空间切换到 Rect
类,正如 Quergo 在他的帖子中显示的那样.
Note, as pointed out above, that the latter is not really possible, as Rectangle
will always be orthogonal, i.e. cannot be rotated, so you will have to go for the corner points. Or switch to the Rect
class from the System.Windows
namespace as Quergo shows in his post.
这篇关于如何使用矩阵旋转矩形并获得修改后的矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!