WinForms控件左上角用图形画矩形切掉矩形左上角各一个像素

Using graphics to draw rectangle at top left corner of WinForms control cuts off one pixel of top and left of rectangle

我有一个 WinForms 项目,我正在尝试在 (0,0)(窗体的左上角)处绘制一个矩形。由于某种原因,它切断了矩形的高度和宽度的一个像素。这是代码:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawRectangle(new Pen(Color.Red, 5), new Rectangle(0, 0, 50, 50));
}

这是结果,为清楚起见放大了:

我知道我可以通过在 (1,1) 处绘制矩形来纠正这个问题,但根据我从放置在 (0,0) 和 ( 1,1).例如,面板在 (1,1) 处的样子,它显然有一个像素的间隙:

所以我的问题是:为什么在 (0,0) 处绘制矩形不像在 (0,0) 处放置控件那样?为什么矩形在顶部和左侧被截断了一个像素?

PenAlignment属性的默认值为PenAlignment.Center,这意味着绘制的线将在线上居中。所以你看到的是意料之中的。

您可能希望将 Alignment 设置为 PenAlignment.Inset:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.DrawRectangle(
        new Pen(Color.Red, 5) { Alignment = PenAlignment.Inset },
        new Rectangle(0, 0, 50, 50));
}

您可能还想阅读 Pen.Alignment 备注:

Center is the default value for this property and specifies that the width of the pen is centered on the outline of the curve or polygon. A value of Inset for this property specifies that the width of the pen is inside the outline of the curve or polygon. The other three values, Right, Left, and Outset, will result in a pen that is centered.