tags:

views:

833

answers:

4
A: 

I guess not... but you may move the drawing position half the pen size to the bottom right

Scoregraphic
+1  A: 

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 believe it handles adjusting the margins for you.

Noldorin
Though it does draw the border right way, for some readon this function uses considerably more processor time than DrawRectangle.
undsoft
@undsoft: Yeah, I wouldn't be too surprised. I'm not sure how it works behind the scenes, but it's certainly a lot more complicated than DrawRectangle, given that's it's capable of drawing 3D and other style borders, among other things.
Noldorin
+1  A: 

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
    }
}
Fredrik Mörk
A: 

You can do this by specifying PenAlignment

Pen pen = new Pen(Color.Black, 2);
pen.Alignment = PenAlignment.Inset; //<-- this
g.DrawRectangle(pen, rect);
phq