Share via


Silverlight 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 as seen here below:

 

(Silverlight 2 RTM required).

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.

In Page.XAML replace <Grid></Grid> with the following:

 <Canvas Background="Black">
     <Image x:Name="FireballLogo" Source="images/Fireballlogo.png">
         <Image.RenderTransform>
             <RotateTransform x:Name="FireballTransform" CenterX="32" CenterY="24"></RotateTransform>
         </Image.RenderTransform>
     </Image>
 </Canvas>

Next, let’s setup our game loop timer using CompositionTarget.Rendering as our looping event. We perform the transform around the center of the image which is 32, 24 since the image is 64x48 in size. For each frame, we increment the angle by one.

 namespace Tip17
 {
     public partial class Page : UserControl
     {
         public Page()
         {
             InitializeComponent();
  
             CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
         }
  
         void CompositionTarget_Rendering(object sender, EventArgs e)
         {
             FireballTransform.Angle += 1; 
             FireballTransform.Transform(new Point(32, 24)); 
         }
     }
 }

Thank you,

--Mike Snow

 Subscribe in a reader

Comments