etoisarobot
etoisarobot

Reputation: 7794

How can I draw a Rectangle on a PictureBox?

I am trying to just draw a Rectangle on a PictureBox that is on a Form.

Writing text like shown here works fine.

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Font myFont = new Font("Arial", 14))
{
    e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
}
}

but when I try to draw a rectangle like so nothing shows up.

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle rect = new Rectangle();
        rect.Location = new Point(25, 25);
        rect.Width = 50;

        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, rect);
        }
    }

What am I missing?

Upvotes: 0

Views: 2593

Answers (2)

Jared Updike
Jared Updike

Reputation: 7277

Perhaps try

Rectangle rect = new Rectangle(new Point(25, 25), new Size(50, 50));

if you like it shorter.

Upvotes: 0

Well, you might have forgot to set rect.Height to something other than 0.

Did you check if the rectangle you're drawing has the correct dimensions?

Upvotes: 4

Related Questions