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

我已经完成了大部分工作.但是,问题出在我的数学计算中.我希望Arrows(用户控件)旋转,使其在wpf中围绕画布“单击时”拖动时指向光标.
我已经弄清楚了如何计算弧度角.但是,当我应用该值时,它似乎无法按预期工作.

当前

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

目标

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

重点关注的主要代码段是…

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>

解决方法:

从本质上讲,这个问题可以归结为找到两个向量之间的夹角,即向量在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值为正),则您知道了角度您旋转时应该为正,反之亦然,这基本上是上述数学的简化直观表示.

任何人-代码.

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&箭头的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);

每当移动到新的图形程序包时,始终需要确定向上的方向和方向.对.如果找不到文档,只需在某处放置一个断点,然后单击左上角和右下角,查看出哪些坐标.

上一篇:DevExpress WPF应用界面开发入门教程 - 打印自定义报表


下一篇:WPF意外行为将ObservableCollection绑定到UserControl