Archive for the ‘animation’ Tag
Animations in Blend
The addition of the animation engine in Windows Presentation Foundation (WPF) allows designers and developers to animate objects without using third party software. Before getting into an example of how to work with animations, it is important to know the basics.
- Animations are time based. After setting a target value the animation interpolates the values from the current value to the target value.
- Storyboards are the container holding animations. Each Storyboard can hold multiple animations.
- Animation types include colors, numeric properties, points, and strings.
A simple example of a ball bouncing will show how to create animations in Blend.
Tip
Press the Shift key while drawing your ellipse. This ensures a perfect circle.
Create the Storyboard
First things first, create a ball. Use the ellipse tool from the toolbox and draw a circle on the Artboard. The next step is to create a Storyboard to hold the ball dropping animation. On the Interactions panel click the plus sign, Figure 1. A box will pop up asking what you would like to name your animation. Everyone has their own naming conventions. For simplicity, this example will stick with the default Storyboard1 name.
After creating the Storyboard you will notice the interface has changed. The Interactions panel expanded, a timeline appeared, and a red border lines the Artboard. This lets you know it is time to animate.
Animation workspaces
Blend accommodates for two different views when designing animations, the Design workspace and the Animation workspace. To switch between views click Window -> Activate Workspace -> Design Workspace/Animation Workspace. Figure 2 and Figure 3 show the difference between the two views.
Figure 3 – Animation workspace

Keyboard shortcut
F6 toggles between the Design Workspace and the Animation Workspace
Add animation to the Stoyboard
Now the Storyboard has been created, add the ball dropping animation. Click on the first second in the timeline, and then move the ball to the bottom of the screen. Notice a white dot appears on the timeline across from the ellipse. This indicates a keyframe has been created for that element at that time. Click on the play icon above the timeline to test the animation.
What values are changing – Transforms
The value that was changed when you moved the ball down was the Y value of the TranslateTransform. Transforms are used for positioning, sizing, and rotating. There are four types of transforms: Translate, Scale, Skew, and Rotate. When moving or sizing in the Artboard, Blend changes the value of the transforms by default. It is possible to animate the Height and Width properties, but you will have to do this by using the property window instead of changing the size of the object on the Artboard.
Every UI element has a Transform. You can find the Transform palette in the properties window. There are six tabs Translate, Rotate, Scale, Skew, Center Point, and Flip in that order.
Make the bounce look natural
Up to this point you only have a ball that falls. There are three actions left to make the ball bounce look more natural: add easing, change the shape of the ball once it hits the ground, and make the ball bounce back up.
Easing
Currently the ball is falling at the same rate, making the animation feel unnatural. In general to make animations more natural you need to add acceleration and deceleration. In Blend this is done by Easing. Click on the white dot on the timeline. The Easing palette appears in the properties window. Click and drag the bottom left dot until you get a curve similar to that in Figure 6. With this curve, the ball will slowly drop then pick up speed as it approaches the ground, simulating gravity.
The ball hits the ground
Think of a racquetball hitting the ground. Once on the ground it changes shape, even if only for a split second. Along with simulating gravity this makes the bouncing ball animation more natural. Just like creating the first animation, click on timeline around 1.2 seconds. Then on the Artboard make the height of the ball smaller. Press play.
Figure 7 – Ball hitting the ground

Finally, make it bounce
Storyboards have the ability to automatically reverse themselves along with repeating the animation. To make the ball bounce you will make the Storyboard reverse and have the behavior repeat. On the Interaction panel click the title of the Storyboard, Figure 8. In the properties window the Common Properties for the Storyboard appear, Figure 9. Check AutoReverse and set the RepeatBehavir to Forever. Press Play
Figure 8

Data visualizations
Today I recieved an e-mail to The Best Tools for Visualization. For the past five years I have worked in a world where there is really only one way to display data, THE GRID. To be exact, the .NET DataGrid. This control alone has employed many developers and has allowed them to make a living (remember The DataGrid Girl?).
These application have pushed the limits on how we think and view data. With Silverlight we have the opputunity join the data visualization revolution. It’s time to get out of the mindset of writing a stored procedures and hooking them to a datagrids. Challenge yourself and your users.
Over the next few weeks I will be working on creating a data visualization project in Silverlight, and I will use the Animation Engine I have created as the basis for motion.
Stay tuned.
Positioning in Silverlight 2
A common mistake in Silverlight is for people to use the Canvas.Left and Canvas.Top property when positioning elements. In Silverlight 2, there is a push towards a relative positioning model. This makes the Margin, HorizontalAlignment, and VerticalAlignment very important (for all you CSS people the Margin starts on the Left and goes clockwise). So, how do you position, move, or animate elements? Where is the X and Y? You can find them in the TranslateTransform which is part of the TransformGroup which is part of the RenderTransform.
XAML (see below for this code to copy)

This is a pain to access from C#. You have to access the TranslateTransform through the Children collection using the index. What happens if you switch the positions of the Transforms in XAML? Your code will fail. Here is the code to access X and Y through C# (again, see below for code to copy).

So my question: Why not add the X, Y, ScaleX, and ScaleY to the UIElement? This would eliminate the need to go through multiple castings in C#, it would prevent index failures if you change your transforms in XAML, and it would eliminate the misuse of the Canvas.Left and Canvas.Top properties.
Code to copy:
<Grid x:Name=”LayoutRoot” Background=”White”>
<Grid.RenderTransform>
<TransformGroup>
<TranslateTransform X=”0″ Y=”0″ />
<ScaleTransform ScaleX=”1″ ScaleY=”0″ />
<RotateTransform Angle=”0″ />
<SkewTransform AngleX=”0″ AngleY=”0″ />
</TransformGroup>
</Grid.RenderTransform>
</Grid>
((LayoutRoot.RenderTransform as TransformGroup).Children[0] as TranslateTransform).X;
((LayoutRoot.RenderTransform as TransformGroup).Children[0] as TranslateTransform).Y;
Easing animations in Expression Blend
Here is how to add easing to your animation in Expression Blend. IMHO adding easing to animations really makes your product look polished. I have been trying to write an Animation system for Silverlight 2, much like the Tweening libraries for Flash and Javascript. However, when I found this today, there may be hope for sticking with Storyboards.
- Create your animation.
- Click on the time node in your animation

- The properties window will display an easing curve once you select the node. Play around with the curve by clicking and drag the yellow dots.

- The resulting XAML<SplineDoubleKeyFrame KeyTime=”00:00:00.5000000″ Value=”1.5″>
<SplineDoubleKeyFrame.KeySpline>
<KeySpline ControlPoint1=”0.282999992370605,0.864″ ControlPoint2=”0.819000005722046,0.049″/>
</SplineDoubleKeyFrame.KeySpline>
</SplineDoubleKeyFrame>
Animation engine for Silverlight
Just added Animations for Width and Height. Check out the code and the example. For more information here is the initial post. I will add more documentation after getting a few more animations in the engine.
Known issues:
After the animation of Width, the width property doesn’t get set. Same with Height.
Reusing a Storyboard
It is possible to reuse a storyboard. Make sure to stop the storyboard before you set a new target property. Thanks Tom for pointing this out.
XAML
<Canvas x:Name=”LayoutRoot” Background=”White”>
<Button Height=”20″ Width=”120″ Canvas.Left=”0″ Canvas.Top=”0″ Content=”Button” x:Name=”btnTest”/>
<Rectangle x:Name=”Fred” Height=”30″ Width=”30″ Fill=”Aquamarine” Canvas.Top=”50″/>
<Rectangle x:Name=”Wilma” Height=”30″ Width=”30″ Fill=”OrangeRed” Canvas.Top=”150″/>
</Canvas>
C#
void Page_Loaded(object sender, RoutedEventArgs e)
{
_storyboard = new Storyboard();
_dx = new DoubleAnimation();
_dx.From = 0;
_dx.To = 250;
_dx.Duration = new Duration(new TimeSpan(0,0,3));
_dx.AutoReverse = true;
_dx.RepeatBehavior = RepeatBehavior.Forever;
Storyboard.SetTargetName(_dx, “Fred”);
Storyboard.SetTargetProperty(_dx, “(Rectangle.Width)”);
_storyboard.Children.Add(_dx);
LayoutRoot.Resources.Add(_storyboard);
_storyboard.Begin();
}
void btnTest_Click(object sender, RoutedEventArgs e)
{
_storyboard.Stop();
Storyboard.SetTargetName(_dx, “Wilma”);
_storyboard.Begin();
}
Animate Silverlight 2 object from 1 line of code
In a previous post about how to create animations dynamically, I showed how to add StoryBoards from C#. I have extracted this logic into a class called SLAnimator. This allows you to do an animation from one line code, and a nice thing about this approach is it still uses the built in Silverlight Animation system.
Here is an example of the code to call the animation.
SLAnimator.Animate(this, rect, 100, 100, 100,1,1);
Parameters:
- Container element
- UIElement to animate
- Time of animation in milliseconds
- X of destination
- Y of destination
- ScaleX
- ScaleY
This animation API is at it’s infancy, so I will continue updating as time permits. Feel free to download the class and give me your feed back.
Enjoy!
How to dynamically create animations from C# in Silverlight
So you want to create an animation from managed code. To do this, there is quite a bit of code needed. For every animation there needs to be a new StoryBoard, and unfortunately a StoryBoard can not be reused between objects. (Correction: You can reuse a dynamically created StoryBoard. Make sure to call StoryBoard.Stop() before setting the new target.)
The approach we are going to take is to animate the TranslateTransforms instead of animating the Canvas.Top and Canvas.Left properties since this is the preferred way of doing animations in WPF. In the below example we will create a rectangle, attached a set of transforms to the rectangle, and dynamically add animations to the rectangle.
- Create a Rectangle

- Create a function that returns a RenderTransform. (I have added more than the TranslateTransform in case you want to access the other transforms at a later time. It’s good practices to have them there.)

- Create a StoryBoard and add DoubleAnimations for both the X and Y.

- Final product

Come back for part 2 and we’ll animate the Scale and add more than one rectangle.
Edit: In case you don’t want to brush off your old OCR programs to get the code, here is a link to the source. Link to working example.
Animating multiple transforms in C# – Silverlight
Yesterday I talked about how to write C# code to animate multiple transforms of an object. It appears, to my dismay, that at the current time you are unable to animate objects completely in C#. There is a work around by creating a XAML storyboard and importing into a string using the XAMLReader object. Here are a few sites that cover this technique.
Silverlight 1.1 Storyboards and Managed Code
Creating animations in code with Silverlight 1.1 (stand November 2007)
Ceating a Game Loop
Animate multiple transforms from C# – WPF
I have been stuck in the world of WPF for a while, hence the lack of posts. Things have calmed down and I am back.
Let’s talk about animating objects in WPF/XAML/C#. Animating multiple transforms in XAML is easy: setup the initial transforms, add a storyboard, set up an event trigger, and go. What about doing this in C#? And how do you animate multiple transforms in a TransformGroup from C#? Let’s take a look:
Overview:
- Create your object (say a rectangle, button, user control, etc.)
- Apply a TransformGroup to the object (add one or more of the following to the TranformGroup: TranslateTransform, ScaleTransform, SkewTransform, or RotateTransform)
- In an event get the TransformGroup of the object and apply a DoubleAnimation to the particular Transform in the group
Screenshot

Code
public Window1()
{
InitializeComponent();
//Create event for the button
btn.Click += new RoutedEventHandler(btn_Click);
//Create a rectangle
Rectangle rect = new Rectangle();
rect.Name = "rect";
rect.Width = 50;
rect.Height = 50;
rect.Fill = Brushes.Beige;
//Add a TransformGroup to the rectangle (note the order)
TransformGroup tg = new TransformGroup();
tg.Children.Add(new TranslateTransform(50.0, 50.0));
tg.Children.Add(new ScaleTransform(1.0,1.0));
tg.Children.Add(new SkewTransform(1.0,1.0));
tg.Children.Add(new RotateTransform(0.0,150.0,150.0));
rect.RenderTransform = tg;
//Add controls to the page
cnvMain.Children.Add(rect);
}
void btn_Click(object sender, RoutedEventArgs e)
{
//Rectangle rect = cnvMain.FindName("rect") as Rectangle;
Rectangle rect = cnvMain.Children[2] as Rectangle;
//Define DoubleAnimation for Translate Transform
DoubleAnimation daTranslateX = GenerateDoubleAnimation(300);
DoubleAnimation daTranslateY = GenerateDoubleAnimation(300);
//Get the TranslateTransform for the rectangle (note Children[0], we added TranslateTransform first)
TranslateTransform tt = (rect.RenderTransform as TransformGroup).Children[0] as TranslateTransform;
//Apply animation to the TranslateTransform
tt.BeginAnimation(TranslateTransform.XProperty, daTranslateX);
tt.BeginAnimation(TranslateTransform.YProperty, daTranslateY);
////Do the same for Scale
DoubleAnimation daScaleX = GenerateDoubleAnimationDouble();
DoubleAnimation daScaleY = GenerateDoubleAnimationDouble();
ScaleTransform sct = (rect.RenderTransform as TransformGroup).Children[1] as ScaleTransform;
sct.BeginAnimation(ScaleTransform.ScaleXProperty, daScaleX);
sct.BeginAnimation(ScaleTransform.ScaleYProperty, daScaleX);
//Do the same for Skew
//DoubleAnimation daSkewX = GenerateDoubleAnimation(45);
//DoubleAnimation daSkewY = GenerateDoubleAnimation(45);
//SkewTransform skt = (rect.RenderTransform as TransformGroup).Children[2] as SkewTransform;
//skt.BeginAnimation(SkewTransform.AngleXProperty, daSkewX);
//skt.BeginAnimation(SkewTransform.AngleYProperty, daSkewY);
//Do the same for Rotate
DoubleAnimation daRotate = GenerateDoubleAnimation(360);
RotateTransform rt = (rect.RenderTransform as TransformGroup).Children[3] as RotateTransform;
rt.BeginAnimation(RotateTransform.AngleProperty, daRotate);
rt.BeginAnimation(RotateTransform.CenterXProperty, daTranslateX);
rt.BeginAnimation(RotateTransform.CenterYProperty, daTranslateY);
}
DoubleAnimation GenerateDoubleAnimation(int max)
{
DoubleAnimation da = new DoubleAnimation();
da.To = randomNumber.Next(max);
da.AccelerationRatio = .8;
da.DecelerationRatio = .1;
da.Duration = new Duration(TimeSpan.FromSeconds(2));
return da;
}
DoubleAnimation GenerateDoubleAnimationDouble()
{
DoubleAnimation da = new DoubleAnimation();
da.To = randomNumber.NextDouble();
da.AccelerationRatio = .8;
da.DecelerationRatio = .1;
da.Duration = new Duration(TimeSpan.FromSeconds(2));
return da;
}
Download the project (not up yet). I am in the process of converting this to a Silverlight project. Please leave me some feedback or questions.
Comments (2)





Leave a Comment
Comments (3)