Tip of the Day #17: How to Animate a Rotating Image
Each Silverlight element exposes a property called RenderTransform that is used to set the transform information that affects the rendering position of the element. I will be demo’ing a non-stop circular transform rotation of an image in a Storyboard timer.
First, let’s declare the the image in our Page.xaml. Make certain to add the image your are setting the source to here to your project in VS. Since we are rotating around the center of the image, we set the CenterX and CetnerY to be the center coordinates of the image which. In my case the image I am using is 64x48 pixels so the center is set at CenterX=32, CenterY=24.
Page.XAML:
<Image x:Name="FireballLogo" Source="images/Fireballlogo.png">
<Image.RenderTransform>
<RotateTransform x:Name="FireballTransform" CenterX="32" CenterY="24">
</RotateTransform>
</Image.RenderTransform>
</Image>
Next, let’s setup our game loop timer using the Storyboard discussed in Tip of the Day #16.
Page.XAML.cs class constructor:
Storyboard _gameLoop = new Storyboard();
public Page()
{
InitializeComponent();
_gameLoop.Duration = TimeSpan.FromMilliseconds(0);
_gameLoop.Completed += new EventHandler(MainGameLoop);
_gameLoop.Begin();
}
And, finally in our MainGameLoop we simply increment the angle by 1 and call Transform on the element to get it to rotate:
void MainGameLoop(object sender, EventArgs e)
{
FireballTransform.Angle += 1;
FireballTransform.Transform(new Point(32, 24));
_gameLoop.Begin();
}
Thank you,
--Mike Snow
Subscribe in a reader