0

I am just playing a little bit with WinForms and C#. Now I am trying to animate a rectangle moving from left edge to the right edge. The animation is working. But the animation isn't smooth. Like the framerate is change a little bit.

Do you have some ideas? I don't want to use graphic libraries (DirectX, OpenGL) etc. and I would prefer to stay in WinForms (I am already working on a wpf-version) and not using BackgroundGraphics. I just want to understand some concepts of 2D/3D and maybe you have some good idea =)

Here my code:

PictureBox pbScreen;
public FormMain()
        {
        ...

        bmpFB = new Bitmap(640, 480);
        bmpBB = new Bitmap(640, 480);

        ...

        tmrTick.Interval = 10;
        tmrTick.Enabled = true;
    }

    private void TmrTick_Tick(object sender, EventArgs e)
    {
        RefreshScreen();
    }

    private void RefreshScreen()
    {
        CalcBackBuffer();
        bmpFB = bmpBB;
        pbScreen.Image = bmpFB;
    }

    private void CalcBackBuffer()
    {
        posX += 1;

        // Collision reaction
        // if the rectangle arrives at the edge, the position X will be resetet to 0
        if (posX > pbScreen.Width)
        {
            posX = pbScreen.Location.X;
        }

        using (Graphics gr = Graphics.FromImage(bmpBB))
        {
            gr.Clear(Color.White);
            gr.FillRectangle(Brushes.Black, new Rectangle(posX, posY, 2, 480));

        }
    }

EDIT: Hm ok, I animated it in a panel, no improvements. Today I coded it in WPF (Rectangle as Canvas.Children) but no improvement. I don't know what the issue is.

My goal is to try out some graphic concepts and start at zero. So the first thing is to translate just one graphic element from one place to another. Then try out double buffering to eliminate flickering. Then VSync to eliminate tearing and so on.

I just need a drawing area where I can draw some pixels at a timer tick.

The movement of the rectangle is not continious. It varies. You can see it stocking. I tried things like Lerp but it is a linear movement, so it doesnt make sense in this case.

  • 1. Create a Panel in your form and draw directly on that. 2. draw using the [Paint Event of the panel](https://stackoverflow.com/questions/5507605/c-sharp-drawing-on-panels) 3. On timer tick Invalidate the panel to refresh. 4. Set DoubleBuffering on the form 5. Do calculation in the tick event (or a function called from that) dont calculate in paint event, save that for drawing only... that should get you somewhere – musefan Jun 01 '17 at 15:53
  • Ok, I will try to draw it on the panel and do the calculation explicit. The double buffering i tried to code on my own. Thank you. – JohnC Dark Jun 01 '17 at 16:08
  • 3
    _Smooth animation with WinForms_ Oxymoron. – TaW Jun 01 '17 at 16:10

0 Answers0