Good afternoon. Tell me how to make smooth animation on WinForms, preferably with control of its speed. The code I use for animation is:

animBW.DoWork += delegate(object sender, DoWorkEventArgs e) { while (true) { int width = panel1.Width; //Random r = new Random(); if (width < this.Width) { int newwidth = width++; setWidth(newwidth); Thread.Sleep(1); } else { break; } } }; 

But with Thread.Sleep (1) the animation is too slow, and depends on the size of the object. (more object => wait more, this is understandable)

In the absence of a pause, the animation is not visible at all.

Tell me how to make the animation independent of the block size and faster?

    2 answers 2

    I suggest using the System.Windows.Forms.Timer class for such purposes. Create a timer, set the interval in milliseconds at which the Tick event will be generated. Assign an event to the event, in which you accumulate the number of steps (for example, into a static variable). If it exceeds what you need, then stop the timer. Sample code to help you.

     private void mainForm_Click(object sender, EventArgs e) { Timer timer = new Timer(); timer.Interval = 30; // каждые 30 миллисекунд int count = 0; int max = 10; Graphics g = this.CreateGraphics(); g.Clear(Color.White); int x = 10; int y = 10; g.DrawEllipse(Pens.Black, x, y, 10, 10); timer.Tick += new EventHandler((o, ev) => { x += 5; y += 5; g.Clear(Color.White); g.DrawEllipse(Pens.Black, x, y, 10, 10); count++; if (count == max) { Timer t = o as Timer; // можно тут просто воспользоваться timer t.Stop(); } }); timer.Start(); // запустили, а остановится он сам } 

    This code on a click moves a circle on an empty form. If you want to, for example, always draw an animation in 1 second, then always take an interval of, say, 10 milliseconds and 100 steps, and change the image parameters to 1/100 of the total change (the difference between the beginning and end of the animation) for each step. You can still reduce the frequency of redrawing for small objects, but this is up to you.

    • Thank! I 'll try a little later .. - AGrief
    • The animation remained as sharp and not beautiful. The timer works like thread.sleep () - AGrief
    • @AGrief 15 frame animation usually looks normal. You can do 1000 frames per second. Your problem, I think, is not in the animation storyboard, but in the rendering speed. For example, the example I cited is not very well drawn (some frames are not visible, the image is twitching), on the pictureBox using Bitmap it will be much better. You want, as I understand it, to redraw the control, which probably redraws itself for a long time and as a result, partially skips frames, and all together flickers. - RussCoder

    Double Buffering will protect from blinking, for smoothness they use Multimedia Timers (Windows API).