Image not Displaying

  • Thread starter Thread starter Barry
  • Start date Start date
B

Barry

Hi

why does the following code not display the image

public Form1()
{
InitializeComponent();

Bitmap imgBg = new Bitmap("Monitor.bmp");
Graphics gr = Graphics.FromImage(imgBg);
gr.DrawImage(imgBg, new Rectangle(10,10, imgBg.Width, imgBg.Height));
}

if i shift the above code in the paint event like this it displays the
bitmap

private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{

Bitmap imgBg = new Bitmap("Monitor.bmp");
e.Graphics.DrawImage(imgBg, new Rectangle(10,10, imgBg.Width,
imgBg.Height));
}


Barry
 
Barry,

The Graphics object does not retain any information about what is actually drawn. You need to redraw the image whenever needed and since Paint is called after the constructor the image will be wiped before you get to see it.

You should and you have put it inside the Paint procedure as this is where you should do all drawing. However, create the bitmap once in the constructor, store the reference and let Paint use that reference when drawing. Creating the bitmap each time Paint is called may slow down the drawing.

Take a look at the GDI+ Faq for more information regarding Paint and drawing (see question #1)

http://www.bobpowell.net/faqmain.htm
 
In the first instance you're trying to draw an image onto itself. This won't
work. In the second you're drawing it onto the form's surface in the correct
manner.

You probably need to be reading the GDI+ FAQ to retain your sanitiy.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Back
Top