首页 > 解决方案 > C# - 在 Windows 窗体中使用图形绘制一个居中的矩形不会给出预期的结果

问题描述

我做了一个小项目来做一些绘图测试。我在 Visual Studio 2019(社区版)下,我正在使用 .Net Framework 4.7.2。

这是上下文:我制作了一个 Windows 窗体项目。我的表单是全屏无边框的,在这种表单中,我有一个CenteredRectanglePanel(继承自 Panel)。该面板占用了我表单中的所有可用空间。所以理论上,面板和我的屏幕大小一样(1920x1080)

我现在想要的是在我的屏幕上绘制一个居中的矩形。

这是我认为可以绘制居中矩形的代码:

public class CenteredRectanglePanel : Panel {

  public CenteredRectanglePanel(Control parent) { // The parent is my form
    var boundsX = parent.Bounds.X + (int) (parent.Bounds.Width * 0.1);
    var boundsY = parent.Bounds.Y + (int) (parent.Bounds.Height * 0.1);
    var boundsWidth = parent.Bounds.Width - 2 * boundsX;
    var boundsHeight = parent.Bounds.Height - 2 * boundsY;
    Bounds = new Rectangle(boundsX, boundsY, boundsWidth, boundsHeight);
    var brush = new SolidBrush(Color.Aqua);
    CreateGraphics().FillRectangle(brush, Bounds);
  }

}

这是我屏幕上的结果:

这里,矩形没有居中

这不是我想要的。如您所见,矩形没有居中。左边的空间似乎比右边的空间大两倍。

但是,如果我更改代码:

public class CenteredRectanglePanel : Panel {

  public CenteredRectanglePanel(Control parent) { // The parent is my form
    var boundsX = parent.Bounds.X + (int) (parent.Bounds.Width * 0.1);
    var boundsY = parent.Bounds.Y + (int) (parent.Bounds.Height * 0.1);
    var boundsWidth = parent.Bounds.Width - 3 * boundsX;
    var boundsHeight = parent.Bounds.Height - 3 * boundsY;
    Bounds = new Rectangle(boundsX, boundsY, boundsWidth, boundsHeight);
    var brush = new SolidBrush(Color.Aqua);
    CreateGraphics().FillRectangle(brush, Bounds);
  }

}

这是结果:

在这里,矩形正确居中

我现在有了预期的结果。我所要做的就是改变2 * boundsXand 和2 * boundsYfor 3 * boundsXand 3 * boundsY

但为什么?我还是不明白。这对我来说是反直觉的。

标签: c#winformsgraphics

解决方案


推荐阅读