Drawing on a panel

C

Chris S.

Here's a starter for 10 - I have the following simple code:

private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.Blue),
this.panel1.ClientRectangle);
}

Where a panel is on a form. I've always had to alter the 'rect'
variable as it doesn't draw the border correctly, the right and bottom
lines aren't in view. Any ideas why this is?
 
L

Larry Lard

Chris said:
Here's a starter for 10 - I have the following simple code:

private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.Blue),
this.panel1.ClientRectangle);
}

Where a panel is on a form. I've always had to alter the 'rect'
variable as it doesn't draw the border correctly, the right and bottom
lines aren't in view. Any ideas why this is?

It looks like there's a difference in meaning between the Rectangles.
This is easier to see if you draw very small controls and look at them
magnified in Paint or such.

- If you have a Panel with Size (2,2) then it does actually have a size
of 2 pixels by 2 pixels

- But if you do a DrawRectangle with a new Rectangle(0, 0, 2, 2) what
you actually get is what I would call a *three by three* rectangle. I
_guess_ this is because the 'zeroth' pixel is counted as well.

So you receive from ClientRectangle the first kind of Rectangle, which
then gets drawn 'one bigger' by DrawRectangle. Whether this is by
design or bug, I couldn't say. The comically auto-generated help is
no... um... help.
 
C

Chris Dunaway

I'm not sure why the rectangle would be off, but I have noticed that
too. But you can minimize it by setting the pen's alignment to inset:

private void panel1_Paint(object sender, PaintEventArge e)
{
Pen p = new Pen(Color.Blue);
p.Alignment = PenAlignment.Inset;
e.Graphics.DrawRectangle(p, panel1.ClientRectangle);

//Be sure the dispose of the pen
p.Dispose();
}

You can experiement with other values of the Alignment property of the
pen.

Hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top