C# DrawPath和DrawRectangle之间的差异

C# DrawPath和DrawRectangle之间的差异,c#,windows,winforms,gdi+,C#,Windows,Winforms,Gdi+,在我的应用程序中,我同时使用矩形和graphicspath绘制线条,当使用graphicspath而不是使用矩形时,我在绘制时面临宽度和高度的损失 下面是复制我的问题的示例代码 protected override void OnPaint(PaintEventArgs e) { int left = ClientRectangle.X + 40, right = ClientRectangle.Width -80; int bottom = ClientRectangle.Heig

在我的应用程序中,我同时使用矩形和graphicspath绘制线条,当使用graphicspath而不是使用矩形时,我在绘制时面临宽度和高度的损失

下面是复制我的问题的示例代码

protected override void OnPaint(PaintEventArgs e)
{
   int left = ClientRectangle.X + 40, right = ClientRectangle.Width -80;
   int bottom = ClientRectangle.Height - 80, top = ClientRectangle.Y + 40;
   int borderWidth = 10;

   Rectangle borderrectangle = new Rectangle(left, top, right, bottom);

   Pen pen = new Pen(Color.Black, borderWidth);

   //Draws lines using Rectangle.
   e.Graphics.DrawRectangle(pen, borderrectangle);

   Point[] points = new Point[]
   {
      new Point(left, top),
      new Point(right, top),
      new Point(right, bottom),
      new Point(left, bottom),
   };

   GraphicsPath path = new GraphicsPath();
   path.AddLines(points);
   path.CloseFigure();

   //Draws lines using Path.
   e.Graphics.DrawPath(pen, path);
}
这是图像

使用DrawPath绘制内部矩形,使用DrawRectangle绘制外部矩形

有谁能告诉我GraphicsPath绘图时宽度和高度丢失的原因,因为我已经给出了矩形的正确点


任何帮助都将不胜感激。

当您创建矩形时,您将通过右下角坐标作为宽度和高度。检查构造函数参数:

public Rectangle(
    int x,
    int y,
    int width,
    int height
)
当您使用路径时,您通过坐标绘制它,一切正常。您应该这样创建矩形:

Rectangle borderrectangle = new Rectangle(left, top, right-left, bottom-top);

但是确保ClientRectangle的宽度和高度大于120

当您为
矩形设置值时,您要设置左上角的X和Y坐标以及宽度和高度。但是,使用
GraphicsPath
,可以明确地将每个角定义为一个单独的点。要使
GraphicsPath
准确地绘制矩形,您需要偏移点阵列坐标以使矩形的宽度和高度相等:

Point[] points = new Point[]
{
   new Point(left, top),
   new Point(right + left, top),
   new Point(right + left, bottom + top),
   new Point(left, bottom + top),
};
或者构造矩形,将
右侧
底部
视为坐标,而不是固定长度:

Rectangle borderrectangle = new Rectangle(left, top, right - left, bottom - top);

考虑到您将这些值视为边和坐标,第二个选项可能会给您带来最大的一致性。

使用DrawPath,您可以绘制许多不规则形状。@LeiYang-当然可以。但是如何在不降低体重和身高的情况下画图呢?看看
矩形的构造器。参数为:
x
y
宽度
高度
除了注释/答案之外,请尝试此
矩形边框矩形=新矩形(左、上、右、左、下、上)并且它们的大小相同