在 Windows 表单应用程序中绘制形状

Draw Shape in Windows Form Application

我想画一个有 4 个角的形状。拐角细节以 X 和 Y 坐标给出(如下图所示)。我尝试了这个 link 给出的方法: Drawing Colors in a picturebox?. But the issue is it only for rectangles.

任何人都可以提出一些建议。我基本上需要它来生成汽车的扫掠路径(汽车在驾驶时占据的区域)。因此,我得到了 X 和 Y 中的汽车中心以及以度数表示的方向。从中我确定了汽车在 X 和 Y space 中的角点。现在我需要展示它 可视化它。请帮忙。

因为你知道旋转度数,所以你可以使用Graphics.RotateTransform。这样你就不需要自己计算角点了(猜猜这个实现更快)。

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.RotateTransform(45 /* your degrees here */);
    e.Graphics.FillRectangle(Brushes.Red, 10, 10, 200, 100);
}

请注意,它围绕 (0;0) 旋转,因此您可能也需要翻译它(使用 Graphics.TranslateTransform)。

你可以使用你的Form/Control的Graphics.DrawPolygon (or Graphics.FillPolygon) method in the OnDraw方法,如下:

protected override void OnPaint(PaintEventArgs e)
{
   // If there is an image and it has a location, 
   // paint it when the Form is repainted.
   base.OnPaint(e);
   PointF[] rotatedVertices = // Your rotated rectangle vertices
   e.Graphics.DrawPolygon(yourPen, rotatedVertices);
   // OR
   e.Graphics.FillPolygon(new SolidBrush(Color.Red), rotatedVertices);
}

您可以使用 Rectangle class 和 Matrix class 创建一个矩形,然后按您的方向旋转它,如下所示:

Graphics g = new Graphics()
Rectangle car = new Rectangle(200, 200, 100, 50)
Matrix m = new Matrix()
m.RotateAt(orientation, new PointF(car.Left + (car.Width / 2), car.Top + (car.Height / 2)));
g.Transform = m
g.FillRectangle(Pens.Red, car)