通过鼠标UWP在View上旋转Ui对象

时间:2016-10-11 10:18:31

标签: c# xaml uwp

我需要使用鼠标为Image进行旋转。 我不知道该怎么做。现在,按下按钮

,我有旋转代码
 private void Rotate_Click(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        var parent = (FrameworkElement) VisualTreeHelper.GetParent(button);
        var ct = (CompositeTransform) parent.RenderTransform;
        ct.Rotation += 5;
    }

但我如何根据自己的要求改变呢?我需要拖动该按钮并旋转

1 个答案:

答案 0 :(得分:0)

以下是拖动视图时围绕其中心旋转的图像的粗略示例。

在新项目中添加此XAML

<Image x:Name="TheImage"
        Source="Assets/StoreLogo.png"
        Width="200"
        Stretch="Uniform"
        RenderTransformOrigin="0.5,0.5"
        PointerPressed="OnPointerPressed"
        PointerMoved="OnPointerMoved"
        PointerReleased="OnPointerReleased">
    <Image.RenderTransform>
        <RotateTransform x:Name="ImageRotation" />
    </Image.RenderTransform>
</Image>

以及随附的代码隐藏

private bool pointerCaptured = false;
private Point lastPosition;

private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
    pointerCaptured = true;
    this.lastPosition = e.GetCurrentPoint(TheImage).Position;
}

private void OnPointerMoved(object sender, PointerRoutedEventArgs e)
{
    if (pointerCaptured)
    {
        Point currentLocation = e.GetCurrentPoint(this.TheImage).Position;

        double radians = Math.Atan((currentLocation.Y - lastPosition.Y) /
                                    (currentLocation.X - lastPosition.X));
        var angle = radians * 180 / Math.PI;

        // Apply a 180 degree shift when X is negative so can rotate all of the way around
        if (currentLocation.X - lastPosition.X < 0)
        {
            angle += 180;
        }

        lastPosition = currentLocation;

        this.ImageRotation.Angle = angle;
    }
}

private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
    pointerCaptured = false;
}

将某些旋转数学的帽子提示到https://stackoverflow.com/a/963099/1755