S.A.Parkhid
S.A.Parkhid

Reputation: 2870

Can't draw on Picturebox

Suppose we have a Form an a picturebox on it:

Where is the problem? Rectangle disapears on picture box. Why?

   private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics gr = pictureBox1.CreateGraphics();
        gr.FillRectangle(Brushes.Red, new Rectangle(10, 10, 50, 50));

    }

Upvotes: 1

Views: 1224

Answers (1)

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

I checked it and yeah the case is what everybody mentioned in comments.

The problem is that you are not taking the reference of Graphics when painting instead just pushing your Rectangle in picturebox's graphics which wont be rendered.

To get it right you will need to use e.Graphics to get a refrence on the graphic that is going to be painted.

So correct code is:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics gr = e.Graphics;
    gr.FillRectangle(Brushes.Red, new Rectangle(10, 10, 50, 50));

}

Upvotes: 1

Related Questions