You can create more realistic animation effects like acceleration and deceleration in Silverlight using keyframes, however, if you’re going to do this by hand (as opposed to using a tool like Blend) you’re going to have to use keysplines which are not immediately intuitive.
For example. Let’s say you want to make the following effect:
See how the blue rectangle falls and then bounces? Here is the XAML code:
<!– This key frame resets the animation to its starting value (30) at the beginning of the animation. –>
<LinearDoubleKeyFrame Value=”30″ KeyTime=”0:0:0″ />
<!– Spline animations are used to create acceleration. This SplineDoubleKeyFrame creates an animation
that starts out slow and then speeds up. The rectangle “falls”. –>
<SplineDoubleKeyFrame KeySpline=”0,0 1,0″ Value=”300″ KeyTime=”0:0:0.8″ />
<!– This spline animation creates the “bounce” at the end where the rectangle shortens its length quickly at first and then
slows down and stops. –>
<SplineDoubleKeyFrame KeySpline=”0.10, 0.21 0.00, 1.0″ Value=”250″ KeyTime=”0:0:1.5″ />
<Rectangle x:Name=”myRectangle” MouseLeftButtonDown=”Mouse_Clicked” Fill=”Blue” Width=”200″ Height=”30″ />
And here is the C#:
// When the user clicks the rectangle, the animation
private void Mouse_Clicked(object sender, MouseEventArgs e)
As you can see, each KeyFrame (the LinearDoubleKeyFrame and two SplineDoubleKeyFrame objects) define one segment (one frame) of the bounce animation. I’m not going to go into detail on KeyFrames in general in this post (see Key-Frame Animations), rather, I want to just discuss the KeySpline property/attribute. The KeySpline attribute in the sample above defines how the Spline Key-Frame interpolates, that is, it defines the accelleration/deceleration you see in the animation.
Ok, if you say so, but what are those numbers that the KeySpline attribute is using (e.g. KeySpline=”0.10, 0.21 0.00, 1.0″)? That attribute is defining a cubic Bezier curve. A cubic Bezier curve is defined by a start point, an end point, and two control points. The KeySpline property of a spline key frame defines the two control points of a Bezier curve that extends from (0,0) to (1,1). The first control point controls the curve factor of the first half of the Bezier curve, and the second control point controls the curve factor of the second half of the Bezier segment. The resulting curve describes the rate of change for that spline key frame. The steeper the curve, the faster the key frame changes its values. As the curve gets flatter, the key frame changes its values more slowly.
The best way to demonstrate a Bezier curve and its effect on interpolation is to show an example. In the example below you change the control points of the Bezier curve, see the effect, and copy down the desired control points for your own applications: