旋转形状以跟随wpf中的光标

时间:2015-12-21 13:49:06

标签: c# wpf xaml

我已经完成了大部分工作。然而,问题出现在我的数学计算中。我希望箭头(用户控件)旋转指向光标,因为它在画布上拖动“点击”#39;在wpf。 我已经弄明白了如何以弧度计算角度。但是,当我应用该值时,它似乎没有按预期工作。

当前

enter image description here

目标

enter image description here enter image description here

焦点的主要代码片段是......

private double Angle(Point origin, Point target)
        {
            //Calculate the distance from the square to the mouse's X and Y position
            var radians = Math.Atan2(origin.Y - target.Y, origin.X - target.X);
            var degrees = radians * (180 / Math.PI) - 90;

            Console.WriteLine(target + "--" + origin + "--" + degrees);
            return degrees;
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {                                     
            var canvas = (Canvas)sender;

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (_followMouse)
                {
                    // Get Cursor Position
                    Point _targetPoint = e.GetPosition(this);

                    // Follow mouse
                    foreach (UIElement element in canvas.Children)
                    {                        
                        Arrow arrow = (Arrow)element;

                        // example 1
                        double x = Canvas.GetTop(arrow) + arrow.ActualWidth / 2.0;
                        double y = Canvas.GetLeft(arrow) + arrow.ActualHeight / 2.0;
                        Point _originPoint = new Point(x,y);

                        arrow.rotateTransform.Angle = Angle(_originPoint, _targetPoint);         
                    }
                }
            }
        }

以下整个项目代码......

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        bool _followMouse;

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _followMouse = true;
        }
        private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            _followMouse = false;
        }

        private double Angle(Point origin, Point target)
        {
            //Calculate the distance from the square to the mouse's X and Y position
            var radians = Math.Atan2(origin.Y - target.Y, origin.X - target.X);
            var degrees = radians * (180 / Math.PI) - 90;

            Console.WriteLine(target + "--" + origin + "--" + degrees);
            return degrees;
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {                                     
            var canvas = (Canvas)sender;

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (_followMouse)
                {
                    // Get Cursor Position
                    Point _targetPoint = e.GetPosition(this);

                    // Follow mouse
                    foreach (UIElement element in canvas.Children)
                    {                        
                        Arrow arrow = (Arrow)element;

                        // example 1
                        double x = Canvas.GetTop(arrow) + arrow.ActualWidth / 2.0;
                        double y = Canvas.GetLeft(arrow) + arrow.ActualHeight / 2.0;
                        Point _originPoint = new Point(x,y);

                        arrow.rotateTransform.Angle = Angle(_originPoint, _targetPoint);         
                    }
                }
            }
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300"
        WindowStartupLocation="CenterScreen">

    <Canvas
        MouseDown="Canvas_MouseDown" 
        MouseUp="Canvas_MouseUp"
        MouseMove="Canvas_MouseMove"
        Background="LightBlue">
        <local:Arrow Canvas.Left="158" Canvas.Top="43"/>
        <local:Arrow Canvas.Left="38" Canvas.Top="108"/>
        <local:Arrow Canvas.Left="158" Canvas.Top="170"/>
        <local:Arrow Canvas.Left="78" Canvas.Top="158"/>
        <local:Arrow Canvas.Left="196" Canvas.Top="108"/>
        <local:Arrow Canvas.Left="78" Canvas.Top="53"/>
    </Canvas>

</Window>

Arrow.xaml

<UserControl x:Class="WpfApplication1.Arrow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="50" d:DesignWidth="50">
    <Grid>
        <Path Data="M 0 4 L 4 0 L 8 4 Z" RenderTransformOrigin="0.5,0.5"
              Width="50"
              Height="50"
              Stretch="Uniform"
              Fill="Red">
            <Path.RenderTransform>
                <RotateTransform x:Name="rotateTransform"/>
            </Path.RenderTransform>

        </Path>
    </Grid>
</UserControl>

3 个答案:

答案 0 :(得分:3)

这个问题基本上归结为找到两个向量之间的角度,矢量为0角(即(0,-1)),矢量从箭头到点击点。

数学是相当简单的,acos(DotProduct(v1,v2)),因为这是一个非常关键的等式,有很多资源可以解释为什么(http://www.wikihow.com/Find-the-Angle-Between-Two-Vectors)。请注意,这会给出矢量之间的无符号角度。要弄清楚这个符号,你应该设置一个等同于vectorTo的DotProduct符号的符号和一个与0向量正交的向量。

用普通(呃)术语来说,假设旋转被应用于时钟的臂,其中0角是12(并且由向量(0,-1)表示)。如果以正角度旋转,则结果将具有正X值,因为手臂的尖端将位于时钟中心的右侧(3个时钟将为(0,1))。向左旋转将给出负值(9点钟将是(0,-1)。因此,如果你知道你想要的结果在右边结束(因为你的X值是正的),那么你知道角度你周围的旋转应该是正面的,反之亦然。这基本上是上面数学的简化视觉表现。

Anywho - 代码。

private double Angle(Point origin, Point target)
{

    // Get the vector from origin->point
    Vector vecTo = target - origin;

    // Normalize the vector
    vecTo.Normalize();

    // 0-angle is pointing straight up, aligned with (0, -1). 
    // The equation for the angle between 2 vectors is acos(Dot(v1, v1))
    // Our DotProduct is trivial, as know v1 is (0, -1).  This exands
    // 0 * v2.X + -1 * v2.Y
    double dotAngle = -vecTo.Y;
    double angle = Math.Acos(dotAngle);

    // Convert to rad
    angle = angle * 180 / Math.PI;
    // ACos will always return a positive number, but because Cos is
    // symmetric around 0 a -ve number is also valid,  Figure out which
    // is correct by taking the Dot vs (1, 0).  If result is positive,
    // then vecTo point in the same general direction as (1, 0), and
    // the angle returned should also be positive.  I've skipped
    // all the actual math, but thats the idea.
    if (vecTo.X > 0)
        return angle;
    else
        return -angle;
}

另一个问题是你的X&amp;箭头的Y坐标相反,应为:

double y = Canvas.GetTop(arrow) + arrow.ActualWidth / 2.0;
double x = Canvas.GetLeft(arrow) + arrow.ActualHeight / 2.0;
Point _originPoint = new Point(x,y);

每当转移到一个新的图形包时,总是需要确定哪个方向上升&amp;对。如果找不到文档,只需在某处放置一个断点,然后单击左上角和右下角,看看哪些坐标是吐出来的。

答案 1 :(得分:0)

In:var angleInRadians = Math.Atan2(yDiff,xDiff)* 180.0 / Math.PI;

Math.Atan2已经以弧度为单位返回向量,因此不需要“* 180.0 / Math.PI”部分。如果您需要将度数重命名为angle而不是angleInRadian。

答案 2 :(得分:0)

我无法回答为什么这是有效的,但我开始假设上下左右是不正确的:你想获得最高点(点数)箭头)。此外,x应该是左边,y应该是顶部。然后添加一半宽度使x成为中心而不是左上角。

double x = Canvas.GetLeft(arrow);
double y = Canvas.GetTop(arrow);
x += (.5*arrow.ActualWidth);

这让我们接近......接下来的部分是我不确定它为何起作用的部分,但似乎有效。也许精通数学的人可以提供帮助。向角度添加90度:

arrow.rotateTransform.Angle = (angleInRadians+90);

我偶然发现了这一点,因为看起来你正在计算的角度是不正确的......通过分析迭代的第一个箭头的顶部和左边的值,我得出结论它是最顶层的。假设,点击左上角区域应该旋转大约270度,但我得到的值更接近180.所以,我添加了90,它似乎适用于任何光标位置,虽然我说的是我&#39;我不知道为什么。