wpf rotate image around center
Asked Answered
K

1

31

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>
Krypton answered 23/10, 2012 at 15:39 Comment(1)
Usually adding a translation before a rotation can sort this.Salted
P
66

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

<Image Source="Images/refresh.jpg" 
    RenderTransformOrigin=".5,.5"
    Height="15">
...
Philippi answered 23/10, 2012 at 15:41 Comment(3)
I get System.UnauthorizedAccessException if I set RenderTransformOrigin before the Rotation, otherwise, without setting it, the Rotation works fine.Garceau
@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...Philippi
Yea, seemed really weird. I created a bug report. I did manage to get it working using a transform though. #74447883Garceau

© 2022 - 2024 — McMap. All rights reserved.