简体   繁体   中英

Rotate image (control) in Silverlight with Transform

I'm trying to rotate an image in Silverlight and can't seem to get it right. I've tried a few different ways so far and can't find the answer.

    <Image Opacity=".5" x:Name="compassImg" Source="compass.png">
        <Image.RenderTransform>
            <RotateTransform x:Name="compassRotator"></RotateTransform>
        </Image.RenderTransform>
    </Image>
 +
    void compass_CurrentValueChanged(object sender, SensorReadingEventArgs<CompassReading> e)
    {
        Dispatcher.BeginInvoke(() =>
        {
            compassRotator.Angle = e.SensorReading.TrueHeading;
        });
    }

and

    <Image Opacity=".5" x:Name="compassImg" Source="compass.png"></Image>
+

    void compass_CurrentValueChanged(object sender, SensorReadingEventArgs<CompassReading> e)
    {
        Dispatcher.BeginInvoke(() =>
        {
            compassImg.RenderTransform = new CompositeTransform() 
            { 
                CenterX = 0.5, 
                CenterY = 0.5, 
                Rotation = e.SensorReading.TrueHeading
            };
            //OR (variations with 0.5 and width / 2 for both composite and rotate
            compassImg.RenderTransform = new RotateTransform()
            {
                CenterX = compassImg.Width / 2,
                CenterY = compassImg.Height / 2,
                Angle = e.SensorReading.TrueHeading
            };
        });
    }

It rotates, but it always rotates around 0/0. What am I doing wrong?

I looked up MSDN, and the second form is correct. http://msdn.microsoft.com/en-us/library/system.windows.media.rotatetransform.centerx.aspx (It is the coordinates, not fraction).

However, if you put a breakpoint where you apply the transform, you may find that Width is NaN. This is because width wasn't set. What you want is the ActualWidth.

One good way for exploration of transforms is to paste the following snippet into your XAML and experiment away.

<StackPanel HorizontalAlignment="Left">
    <TextBlock>Center X</TextBlock>
    <Slider  
        Name="RTX" Minimum="0.0" Maximum="116"  />
    <TextBlock>Center Y</TextBlock>
    <Slider 
        Name="RTY" Minimum="0.0" Maximum="800"/>
    <TextBlock>Angle</TextBlock>
    <Slider 
        Name="Angle" Minimum="0.0" Maximum="360" />
</StackPanel>

<Image Source="{Binding ImagePath}" Name="image1">
    <Image.RenderTransform>
        <RotateTransform Angle="{Binding ElementName=Angle,Path=Value}"
             CenterX="{Binding ElementName=RTX, Path=Value}"
             CenterY="{Binding ElementName=RTY, Path=Value}"/>                
    </Image.RenderTransform>
</Image>

您需要将RenderTransformOrigin属性设置为“ 0.5,0.5 ”,这将使元素绕其中心旋转。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM