0

I need make rotation for Image by using mouse. I dont know how to do it. Now I have code for rotating by pressing on the button

 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;
    }

But how I can change it to my requirements? I need drag that button and rotate

SmiLe
  • 311
  • 2
  • 13

1 Answers1

0

Here's a crude example of an image on a view that rotates around its center when dragged.

In a new project add this 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>

and here's the accompanying code-behind

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;
}

Hat tip for some of teh rotation math to https://stackoverflow.com/a/963099/1755

Community
  • 1
  • 1
Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
  • Hm, I have some troubles with implementation. I cannot set `` because I have `CompositeTransform` and I need Drag a button witch placed in a neighbor cell near image. And my Grid place is DataTemplate http://joxi.ru/Dr83OBecLD1JA6 Does your method can be implement to my structure? – SmiLe Oct 12 '16 at 09:09