Search code examples
c#wpfvisual-studio-2019.net-4.5

Rotating an arc of circumference continuously forever by applying rotations form 0 to 360 to simulate an animated spinner


I have below drawing image which is an arc of a circumference and now I would like to apply rotations from 0 to 360 in a loop indefinitely to simulate a spinner animated. Something like you can see here, an arc of circumference rotating forever.

enter image description here

<DrawingImage x:Key="ico_spinnerDrawingImage">
  <DrawingImage.Drawing>
    <DrawingGroup ClipGeometry="M0,0 V12 H12 V0 H0 Z">
      <DrawingGroup.Transform>
        <TranslateTransform X="9.5367397534573684E-07" Y="1.1465158453161615E-14" />
      </DrawingGroup.Transform>
      <GeometryDrawing Brush="#FF00AA2B" Geometry="F1 M12,12z M0,0z M12,12C12,10.4241 11.6896,8.86371 11.0866,7.4078 10.4835,5.95189 9.59958,4.62902 8.48528,3.51472 7.37098,2.40042 6.04811,1.5165 4.5922,0.913445 3.13629,0.310389 1.57586,-6.88831E-08 -9.53674E-07,0L0,3C1.1819,3 2.35222,3.23279 3.44415,3.68508 4.53608,4.13738 5.52823,4.80031 6.36396,5.63604 7.19969,6.47177 7.86262,7.46392 8.31492,8.55585 8.76721,9.64778 9,10.8181 9,12L12,12z" />
    </DrawingGroup>
  </DrawingImage.Drawing>
</DrawingImage>

Above drawingimage is inclosed within a dictionary that I import to my WPF view and I associate it to the source property of an WPF image by doing this (i removed the not relevant properties):

    <Image Source="{Binding Path=MySpinnerIcon}"/>

Now, how can apply that animation to the drawingimage to simulate an animated spinner circling continuously forever?


Solution

  • You may animate the Angle property of a RotateTransform that is used as the RenderTransform of a UI element.

    The animation itself is performed by a DoubleAnimation in a StoryBoard that can for example be started by an EventTrigger on the Loaded event of the UI element.

    The example below uses a simple Path element instead of an Image. It draws a 20 units wide elliptical arc with round ends and radius 90 into a 200x200 box.

    <Path Data="M100,10 A90,90 0 0 1 190,100"
          Width="200" Height="200"
          Stroke="Turquoise" StrokeThickness="20"
          StrokeStartLineCap="Round" StrokeEndLineCap="Round"
          RenderTransformOrigin="0.5,0.5">
        <Path.RenderTransform>
            <RotateTransform />
        </Path.RenderTransform>
        <Path.Triggers>
            <EventTrigger RoutedEvent="Loaded">
                <BeginStoryboard>
                    <Storyboard TargetProperty="RenderTransform.Angle">
                        <DoubleAnimation By="360" Duration="0:0:1"
                                         RepeatBehavior="Forever"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Path.Triggers>
    </Path>