c# - 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 * boundsX
and 和2 * boundsY
for 3 * boundsX
and 3 * boundsY
。
但为什么?我还是不明白。这对我来说是反直觉的。
解决方案
推荐阅读
- entity-framework - 你可以在实体框架中使用文件流吗
- python - Pytorch RuntimeError:大小不匹配,m1:[1 x 7744],m2:[400 x 120]
- reactjs - 无法在 onClick 中读取“someFunction”的 null 属性“someFunction”
- java - 如何计算这些重复的整数?
- momentjs - 一时误会 utcOffset
- javascript - jQuery 单选按钮事件
- sql - Apex 身份验证包
- python - 在一个 GPU 上多线程处理两个不同的神经网络是否有意义?
- jquery - 使用 jquery ajax 替换视图部分
- angular - 具有多个组件的 Angular LazyLoading 不起作用