Sign in to follow this  
silverphyre673

[.net] Holy cow I've started a lot of threads lately - Form.Paint not being called

Recommended Posts

I've got a question about loading a Bitmap from a file and displaying it on a form. First off, can a Bitmap object load a png file? A picturebox control can, so I'm just checking to make sure a Bitmap can as well. Secondly and more importantly, I tried this code:
private void TestForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Bitmap myBitmap = new Bitmap("Media/grass.png");
            g.DrawImage(myBitmap, new RectangleF(0, 0, 64, 64));
        }
Which I know is stupid for loading a graphic each frame, but I'll solve that once I can actually get the image to display. Actually, what the problem is is that this function never gets called, which I determined by setting a breakpoint in it. The Load function gets called and the form gets displayed, but this particular function never gets called. How come, and how do I fix this problem? Thanks very much.

Share this post


Link to post
Share on other sites
Did you set up the event handler for it?

private void InitializeComponent()
{

//stuff removed for brevity
//...

this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);

}



You might also want to not load the bitmap in the Paint event:

        private Bitmap _img;

public Form1()
{
InitializeComponent();

_img = new Bitmap("media/grass.png");
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(_img,new RectangleF(0, 0, 64, 64));
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You might also want to call this.Invalidate() at the end of the Paint event, if you want the form to be redrawn repeatedly.

Opinion: Instead of hooking up an event handler, override OnPaint. For example:


protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint();

Graphics g = e.Graphics;

Bitmap myBitmap = new Bitmap("Media/grass.png");

g.DrawImage(myBitmap, new RectangleF(0, 0, 64, 64));

}


Just make sure to call base.OnPaint() at the start of the function. Check MSDN for more information.

Share this post


Link to post
Share on other sites
Plus, if you are going to keep the Bitmap call in the on paint method, be sure to .Dispose() it at the end, or wrap it in a using block so it gets disposed automatically. Yes... C# is a garbage collected language and eventually will clean up all that for you, but it was thrash the hell out of memory in the meantime allocating such a large object so often.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this