Search code examples
c#winformsperformancesystem.drawing

Image draw speed


i am working on a game, but currently I am running benchmarks.

If anyone can help me on this matter, I would greatly appreciate it.

What I am doing, is I fire the paint event on a panel when I click the start button, with this code:

    private void startToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            pnlArea.Invalidate();

        }
        catch (Exception)
        {
            throw;
        }
    }

I then do this in my paint event:

    private void pnlArea_Paint(object sender, PaintEventArgs e)
    {
        try
        {
            stopwatch = new Stopwatch();
            // Begin timing
            stopwatch.Start();

            if (gameStatus == GameStatus.PlaceHead)
            {
                e.Graphics.DrawImage(dictHead["HeadRight"], 100, 100, 15, 15);
            }

            //e.Graphics.Clear(Color.White);

            if (gameStatus == GameStatus.GameTest)
            {
                int x = 0;
                int y = 0;
                for (int i = 0; i < 5000; i++)
                {
                    x += 15;
                    if (x > 1000)
                    {
                        x = 0;
                        y += 15;
                    }

                    e.Graphics.DrawImage(body.Value, x, y, 15, 15);

                }
            }

            toolTimer.Text = Math.Round((stopwatch.Elapsed.TotalMilliseconds / 1000), 2).ToString() + "s";

            // Stop timing
            stopwatch.Stop();
        }
        catch (Exception)
        {

            throw;
        }
    }

This is the body part I am drawing in the code above:

enter image description here

This is the exact size --> 15px x 15px

but this takes up to 1.2 seconds sometimes!!! is there a way I can improve this?

this is a sample of the end result screen: enter image description here


Solution

  • In addition to the information everyone gave me, I came to the conclution to double buffer the panel. This fixed my problem -->

    class DoubleBufferedPanel : Panel { public DoubleBufferedPanel() : base() { DoubleBuffered = true; } }
    

    And I just used this double buffered panel instead.

    New benchmark with no flickering at all! : enter image description here