Wednesday, April 6, 2011

Animate Image Left To Right

The basics of any animation is moving something from one location to the other. In this code snippet I use to Image elements to slide away previously selected image and slide in the newly selected one.


The Image elements need to sit in a Canvas in order to let the Left property make sence.
<Label x:Name="txtFile"  HorizontalAlignment="Stretch"  />
<Canvas HorizontalAlignment=
"Stretch" VerticalAlignment="Stretch">

<Image x:Name=
"newImage" Canvas.Left="0" Canvas.Top="0" />
<Image x:Name=
"oldImage" Canvas.Left="0" Canvas.Top="0" />

</Canvas>



assuming that I have already given the previously selected image, my new image file will be given through a function call like
AnimateLeftToRight(selectedFile);

This method will swap the images and create a storyboard to begin animating. I start the newImage from x-position that equals to minus Window.Width and the old one starts from 0 and moves to Window.Width:


/// <summary>
/// Begins a story which animates two images from left to right
/// the old image takes the source from te new image just before assigning the new one
/// and they move together in the distance of Window.Width
/// </summary>
/// <param name="path">the path of the new image</param>
private void AnimateLeftToRight(string path)
{
oldImage.Source = newImage.Source;
newImage.Source =
new BitmapImage(new Uri(path));

var myStoryboard =
new Storyboard();

myStoryboard.Children.Add(MakeAnimation(-
this.Width, 0, "newImage"));
myStoryboard.Children.Add(MakeAnimation(
0, this.Width, "oldImage"));

myStoryboard.Begin(
this);
}



Making animation can be done in different ways using different EasingFunction, But this one looked easy to understand and look nice on my example:


/// <summary>
/// Creates a DoubleAnimation that moves the target from left to right
/// </summary>
/// <param name="from">starting point X</param>
/// <param name="to">ending point X</param>
/// <param name="target">the target element to set the x to </param>
/// <returns>the created animation</returns>
private DoubleAnimation MakeAnimation(double from, double to, string target)
{
const double durationSeconds = 1;

var animation =
new DoubleAnimation
{
Duration =
new Duration(TimeSpan.FromSeconds(durationSeconds)),
AutoReverse =
false,
From = from,
To = to,
EasingFunction =
new PowerEase()
{
EasingMode = EasingMode.EaseInOut,
Power =
5
}
};

Storyboard.SetTargetName(animation, target);
Storyboard.SetTargetProperty(animation,
new PropertyPath(Canvas.LeftProperty));

return animation;
}