DrawRectangle中的边框

und*_*oft 27 c# graphics

好吧,我正在为我自己的控件编写OnPaint事件编码,对我来说这是非常必要的,以使其像素精确.

我对矩形边框有一点问题.

见图:

删除了死的ImageShack链接

这两个矩形使用相同的位置和大小参数绘制,但使用不同大小的笔.看看发生了什么?当边框变大时,它会占据矩形之前的自由空间(左侧).

我想知道是否有某种属性使得边框被绘制在矩形内部,因此到矩形的距离将始终相同.谢谢.

hul*_*ist 52

您可以通过指定PenAlignment来完成此操作

Pen pen = new Pen(Color.Black, 2);
pen.Alignment = PenAlignment.Inset; //<-- this
g.DrawRectangle(pen, rect);
Run Code Online (Sandbox Code Playgroud)

  • 我发现了一个警告;如果边框宽度为 1 像素,则不会在右侧和底部绘制边框。我通过指定这样的矩形来修复它(如果画笔宽度为 1 像素宽,则从宽度和高度中减去 1 像素): New Rectangle(0, 0, width - If(pen.Width &gt; 1, 0, 1), height - If(画笔宽度 &gt; 1, 0, 1))) (3认同)

Fre*_*örk 6

如果希望矩形的外边界在所有方向上受到约束,则需要根据笔宽度重新计算它:

private void DrawRectangle(Graphics g, Rectangle rect, float penWidth)
{
    using (Pen pen = new Pen(SystemColors.ControlDark, penWidth))
    {
        float shrinkAmount = pen.Width / 2;
        g.DrawRectangle(
            pen,
            rect.X + shrinkAmount,   // move half a pen-width to the right
            rect.Y + shrinkAmount,   // move half a pen-width to the down
            rect.Width - penWidth,   // shrink width with one pen-width
            rect.Height - penWidth); // shrink height with one pen-width
    }
}
Run Code Online (Sandbox Code Playgroud)