WPF rotate animation

Pablo Molina picture Pablo Molina · Oct 14, 2010 · Viewed 12.2k times · Source

I'm working with WPF and I can't achieve an animation.

I have a rectangle which rotates from x degree with a render transform origin from 0,0. I want this rectangle to rotates from y degrees with a render transform origin from 0,1 after 2 seconds.

Of course I want to keep the rectangle position for the second animation.

My problem is when I change the rendertransform origin and apply the second rotation the current position is not kept and he moves from the initial location.

Any idea how I can achieve this?

Thank's for helping.

<Window x:Class="SimpleMove"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="OpenWWindow" Height="900" Width="900">
  <Grid >
    <Rectangle Name="rec1" Width="100" Height="400" Fill="DimGray" RenderTransformOrigin="0,0">
      <Rectangle.RenderTransform>
        <RotateTransform x:Name="Rec1_Rotate"/>
      </Rectangle.RenderTransform>
    </Rectangle>

    <Button Width="45" Height="30" Name="Button1">Start
      <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
          <EventTrigger.Actions>
            <BeginStoryboard>
              <Storyboard TargetProperty="Angle">                
                <DoubleAnimation Storyboard.TargetName="Rec1_Rotate" By="40" Duration="00:00:1" BeginTime="00:00:00"/>                                                
                <PointAnimation Storyboard.TargetName="rec1" Storyboard.TargetProperty="RenderTransformOrigin" To="0,1" Duration="00:00:0" BeginTime="00:00:02" />
                <DoubleAnimation Storyboard.TargetName="Rec1_Rotate" By="-80" Duration="00:00:2" BeginTime="00:00:03"/>
              </Storyboard>
            </BeginStoryboard>
          </EventTrigger.Actions>
        </EventTrigger>
      </Button.Triggers>
    </Button>
  </Grid>
</Window>

Answer

Scott Boettger picture Scott Boettger · Oct 15, 2010

RenderTransformOrigin refers to the starting point of, in this case, the rectangle in the window. When you rotate based on point (0,0) the rectangle will rotate around the top left corner of itself. If you change the RenderTransformOrigin to now rotate around (0,1) you are not rotating now based on the bottom left corner of the rectangle in it's current position but you are rotating based on the original position of the rectangle. My thoughts on this would be to set the render transform origin to something like (0,0.5) to get the rocking motion you are looking for.