Animations: Sliding & Fading controls on a C# form (winforms)
Check out the dot-net-transitions project on Google Code. There's now a clone on Github here. It's also available on nuget as dot-net-transitions
. It supports a variety of linear/non-linear transitions including composite transitions that can be used for more complex effects such as ripple.
Here is a working sample that demonstrates your desired behavior:
var pictureBox = new PictureBox
{
ImageLocation = "http://icons2.iconarchive.com/icons/klukeart/summer/128/hamburger-icon.png",
SizeMode = PictureBoxSizeMode.AutoSize
};
var textBox = new TextBox
{
Text = "Hello World",
Location = new Point(140, 140)
};
var form = new Form
{
Controls =
{
textBox,
pictureBox
}
};
form.Click += (sender, e) =>
{
// swap the Left and Top properties using a transition
var t = new Transition(new TransitionType_EaseInEaseOut(1000));
t.add(pictureBox, "Left", textBox.Left);
t.add(pictureBox, "Top", textBox.Top);
t.add(textBox, "Left", pictureBox.Left);
t.add(textBox, "Top", pictureBox.Top);
t.run();
};
form.ShowDialog();
I recommend that you switch to WPF; that would make it far easier.
It is completely impossible to fade controls in WinForms; Windows controls cannot have opacity.
The closest you can get would be to render the control and its area on the form to a pair of bitmaps, then crossfade the bitmaps in a PictureBox using a ColorMatrix.
To slide controls in WinForms, you can use a Timer to gradually change the Top
and/or Left
properties of the controls and move them across the form. However, you'll get an annoying flicker, which is (AFAIK) impossible to remove.
You could do this in WinForms, with a great deal of effort, so I would have to second the recommendations to use WPF (which is essentially built for exactly this kind of thing).
Your main obstacle to doing this in WinForms is the fact that a control location is specified by integer, which means you can't set a control's Left
property to 45.3425
, for example. This basically makes smooth animation of controls (assuming you want movement that changes speeds and directions) completely impossible - you will get an unavoidable jerkiness of movement this way (I've tried, so I know).
As SLaks suggested, the only way to do this in WinForms would be to "fake" it by taking "snapshots" of each control. Basically, you would start with an invisible Bitmap the size of your form, drawn with the form's BackColor. You would then create the "snapshots" by calling DrawToBitmap() on each control you wish to animate, and create the movement effect by drawing the snapshots onto the canvas (System.Drawing
can draw images with floating-point coordinates, avoiding the jerkiness of integer locations).
This is too much damn work, though. Just use WPF. :)
Edit: I should mention that it's actually easy to do something like this in WinForms, as long as you don't mind it looking awful and jerky and amateurish. My above comments refer to the difficulties of doing this well.