30

I have an image on a button which I would like to rotate when the user clicks it. I allmost have it to work. The image rotates fine on click, but it doesn't rotate round its center.

How can I make the image rotate around its center and not the top left corner?

Here is my code:

<Button Name="btnRefreshPortList"
    Grid.Column="1"
    Margin="10 0 0 0"
    Command="{Binding RefreshPortList}">
                        
    <Image Source="Images/refresh.jpg" 
        Height="15">
        <Image.RenderTransform>
            <RotateTransform x:Name="AnimatedRotateTransform" Angle="0" />
        </Image.RenderTransform>
        <Image.Triggers>
            <EventTrigger RoutedEvent="MouseDown">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="AnimatedRotateTransform" 
                            Storyboard.TargetProperty="Angle" 
                            By="10"        
                            To="360" 
                            Duration="0:0:0.5" 
                            FillBehavior="Stop" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Image.Triggers>
    </Image>
</Button>
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
7heViking
  • 7,137
  • 11
  • 50
  • 94

1 Answers1

63

Just set RenderTransformOrigin to (0.5, 0.5) on the image

<Image Source="Images/refresh.jpg" 
    RenderTransformOrigin=".5,.5"
    Height="15">
...
Cellcon
  • 1,245
  • 2
  • 11
  • 27
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • I get System.UnauthorizedAccessException if I set RenderTransformOrigin before the Rotation, otherwise, without setting it, the Rotation works fine. – John Glen Nov 15 '22 at 02:59
  • @JohnGlen that's weird... UnauthorizedAccessException is a security-related error. I see no reason why it should be thrown in this case. Looks like a bug in WPF... – Thomas Levesque Nov 15 '22 at 16:09
  • Yea, seemed really weird. I created a bug report. I did manage to get it working using a transform though. https://stackoverflow.com/questions/74447383/how-do-you-rotate-an-image-around-its-center-point-in-a-c-sharp-code-behind-file/74447401#74447401 – John Glen Nov 15 '22 at 23:11