Simple animation in WinForms

Imagine you want to animate some object in WinForm. You set a timer to update the state or model and override the form draw event. But from there, what's the best way to constantly redraw a form for animation?

  • Invalidity of a form, as soon as you finish drawing?
  • Set a second timer and cancel the form at a regular interval?
  • Perhaps there is a common template for this thing?
  • Are there any useful .NET classes to help?

Every time I need to do this, I discover a new method with a new flaw. What are the experiences and recommendations of the SO community?

+19
animation winforms
Aug 14 '08 at 16:44
source share
3 answers

In some situations, it’s faster and more convenient not to draw using the paint event, but getting the Graphics object from the control / form and drawing β€œon”. This can lead to some trouble with opacity / anti-aliasing / text, etc., but it can be worth the trouble in terms of having to repaint the entire shabang. Something like:

private void AnimationTimer_Tick(object sender, EventArgs args) { // First paint background, like Clear(Control.Background), or by // painting an image you have previously buffered that was the background. animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++])); } 

I use this in some controls myself and buffered images β€œclear” the background when the object of interest moves or needs to be deleted.

+9
Aug 14 '08 at 17:39
source share

I created a library that can help with this. It is called Transitions and can be found here: http://code.google.com/p/dot-net-transitions/

It uses timers running on the background thread to animate objects. The library is open source, so if you find it useful, you can look at the code to see what it does.

+44
Jul 20 '09 at 21:10
source share

What you do is the only solution I have ever used in WinForms (timer with constant redraws). There are many methods you can use to make the user smoother (like double buffering).

You might want to try WPF. There are built-in animation tools in WPF, and they are much smoother (and require less code and no synchronization on your part) than a timer-based solution.

Note that you do not need to use WPF for your entire application for this solution; you can pack this functionality into a WPF control and embed the control into a WinForms application (or an unmanaged application, for that matter):

http://www.codeproject.com/KB/WPF/WPF_UserControls.aspx

+3
Aug 14 '08 at 16:50
source share



All Articles