Saturday, 25 August 2012

How to animate a rotating image in Silverlight

Each Silverlight element has a property called RenderTransform that is used to set the transform information that affects the loading position of the element.This article deals with rotating image in silverlight.

First, declare the image in our Page.xaml. To rotate the image around its center, set the CenterX and CetnerY to be the center coordinates of the image which. In my case the image I am using is 128x96 pixels so the center is set at CenterX=64, CenterY=48.

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

<Canvas Background="Black">
    <Image x:Name="busyIndicatorLogo" Source="images/ busyIndicatorLogo.png">
        <Image.RenderTransform>
            <RotateTransform x:Name=" busyIndicatorLogoTransform" CenterX="64" CenterY="48"></RotateTransform>
        </Image.RenderTransform>
    </Image>
</Canvas>


We perform the transform around the center of the image which is 64, 48 since the image is 128x96 in size. For each frame, we increment the angle by one.
namespace SilverlightApp
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            busyIndicatorLogoTransform.Angle += 1;
            busyIndicatorLogoTransform.Transform(new Point(64, 48));
        }
    }
}
Post a Comment