James Aharon
James Aharon

Reputation: 223

How can i draw a rectangle around the pictureBox1 borders?

In the pictureBox1 paint event i tried to draw a rectangle around the Image in the pictureBox1:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {           
                e.Graphics.DrawRectangle(new Pen(Brushes.Red, 5), new Rectangle(0, 0, pictureBox1.Image.Width,
                    pictureBox1.Image.Height));           
        }

But what i get is this:

Rectangle around image

And i also tried to draw a rectangle aorund the pictureBox1 it self:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawRectangle(Pens.Green, 0, 0
                                     , pictureBox1.Width, pictureBox1.Height);
        }

But in this case i'm getting a thick green line only on the left and the top the right and bottom without green.

Rectangle around pictureBox

The pictureBox1 in the desinger it's property SizeMode is set to StretchImage How can i draw the rectangles in both cases ?

And how the property of the top line i called ? It's not Height maybe top ? If i want to find and draw only on the top of the pictureBox how does it called ?

Upvotes: 2

Views: 1631

Answers (1)

user3311691
user3311691

Reputation:

To draw inside picturebox it is easy:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    float penWidth = 5F;
    Pen myPen = new Pen (Brushes.Red, (int)penWidth);
    e.Graphics.DrawRectangle(myPen, penWidth / 2F, penWidth / 2F, 
                             (float)pictureBox1.Width - 2F * penWidth, 
                             (float)pictureBox1.Height - 2F * penWidth);

    myPen.Dispose();
}

To draw outside picturebox you need to know which control is underneath it. eg if it is your form then use form paint:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    int lineWidth = 5;
    Brush  myBrush = new SolidBrush (Color.Green);
    e.Graphics.FillRectangle(myBrush, pictureBox1.Location.X - lineWidth, 
          pictureBox1.Location.Y - lineWidth, pictureBox1.Width + 2 * lineWidth, 
          pictureBox1.Height + 2 * lineWidth);

    myBrush.Dispose();
}

I am using FillRectangle because the part that is under picturebox is not visible and it is easier to control the width.

Upvotes: 2

Related Questions