Recently I created a little Silverlight application called “LittleMath”. It is a simple number addition game. It randomly generate two numbers between 0 and 9. The user clicks on the number pad to give the answer and check it by clicking on “Check Answer”. This is my first Silverlight application. I found it very interesting. With the help of Expression Blend, you can build nice looking application with animation fairly quickly. However, sometimes you may need to animation programmatically. In my demo, when you check “Show Beads”, it will show the red beads one by one according to the randomly generated numbers. Here is how to do it.
First we create a story board and animation duration for each bead:
private double beadDuration = 0.5;
private Storyboard showBeadsStoryBoard = new Storyboard();
Then add the story board to resources with a name
LayoutRoot.Resources.Add("showBeads", showBeadsStoryBoard);private void ShowBeads()
{
ClearBeads();
int num1 = Convert.ToInt32(number1.Text);
int num2 = Convert.ToInt32(number2.Text);
Duration storyBoardduration = new Duration(TimeSpan.FromSeconds(beadDuration * (num1 + num2)+1));
showBeadsStoryBoard.Duration = storyBoardduration;
Duration duration = new Duration(TimeSpan.FromSeconds(beadDuration));
for (int i = 0; i < num1; i++)
{
AddBead(beadsPanel1, TimeSpan.FromSeconds(beadDuration * i + 1), duration);
}
for (int i = 0; i < num2; i++)
{
AddBead(beadsPanel2, TimeSpan.FromSeconds(beadDuration * (num1 + i) + 1), duration);
}
// Begin the animation.
showBeadsStoryBoard.Begin();
}
private void AddBead(StackPanel beadsPanel, TimeSpan beginTime, Duration duration)
{
// Add bead
Ellipse bead = new Ellipse();
bead.Width = 20;
bead.Height = 20;
bead.Margin = new Thickness(0);
bead.Fill = beadBrush;
bead.Opacity = 0;
beadsPanel.Children.Add(bead);
// Add animation
DoubleAnimation beadDoubleAnimation = new DoubleAnimation();
beadDoubleAnimation.Duration = duration;
beadDoubleAnimation.BeginTime = beginTime;
showBeadsStoryBoard.Children.Add(beadDoubleAnimation);
Storyboard.SetTarget(beadDoubleAnimation, bead);
Storyboard.SetTargetProperty(beadDoubleAnimation, new PropertyPath("(UIElement.Opacity)"));
beadDoubleAnimation.To = 1;
}
private void ClearBeads()
{
showBeadsStoryBoard.Stop();
beadsPanel1.Children.Clear();
beadsPanel2.Children.Clear();
}
No comments:
Post a Comment