C# DrawRectangle 中的边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/925509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Border in DrawRectangle
提问by undsoft
Well, I'm coding the OnPaint event for my own control and it is very nescessary for me to make it pixel-accurate.
好吧,我正在为我自己的控件编写 OnPaint 事件,这对我来说是非常必要的。
I've got a little problem with borders of rectangles.
我对矩形的边界有一点问题。
See picture:
见图片:
removed dead ImageShack link
删除了无效的 ImageShack 链接
These two rectangles were drawn with the same location and size parameters, but using different size of the pen. See what happend? When border became larger it has eaten the free space before the rectangle (on the left).
这两个矩形使用相同的位置和大小参数绘制,但使用不同大小的笔。看看发生了什么?当边框变大时,它已经吃掉了矩形(左侧)之前的可用空间。
I wonder if there is some kind of property which makes border be drawn inside of the rectangle, so that the distance to rectangle will always be the same. Thanks.
我想知道是否有某种属性可以在矩形内部绘制边框,以便与矩形的距离始终相同。谢谢。
采纳答案by hultqvist
You can do this by specifying PenAlignment
您可以通过指定PenAlignment来做到这一点
Pen pen = new Pen(Color.Black, 2);
pen.Alignment = PenAlignment.Inset; //<-- this
g.DrawRectangle(pen, rect);
回答by Scoregraphic
I guess not... but you may move the drawing position half the pen size to the bottom right
我想不是......但你可以将画笔大小的一半移动到右下角
回答by Noldorin
This isn't a direct answer to the question, but you might want to consider using the ControlPaint.DrawBorder
method. You can specify the border style, colour, and various other properties. I also believeit handles adjusting the margins for you.
这不是问题的直接答案,但您可能需要考虑使用该ControlPaint.DrawBorder
方法。您可以指定边框样式、颜色和各种其他属性。我也相信它可以为您调整边距。
回答by Fredrik M?rk
If you want the outer bounds of the rectangle to be constrained in all directions you will need to recalculate it in relation to the pen width:
如果您希望矩形的外边界在所有方向上都受到约束,则需要根据笔宽重新计算它:
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
}
}