获取WPF中鼠标位置相对于圆心的角度的最简单方法
当鼠标移动时,我有一个圆圈,我可以得到e.GetPosition(这个)。但是如何通过编程获得相对于圆心的角度呢 我在网上看到一些用XAML绑定的时钟样本。这不是我想要的,我想要从鼠标相对于圆心的位置得到角度值 这就是我所尝试的:获取WPF中鼠标位置相对于圆心的角度的最简单方法,wpf,wpf-controls,Wpf,Wpf Controls,当鼠标移动时,我有一个圆圈,我可以得到e.GetPosition(这个)。但是如何通过编程获得相对于圆心的角度呢 我在网上看到一些用XAML绑定的时钟样本。这不是我想要的,我想要从鼠标相对于圆心的位置得到角度值 这就是我所尝试的: private void ellipse1_MouseMove(object sender, MouseEventArgs e) { Point position = e.GetPosition(this); doub
private void ellipse1_MouseMove(object sender, MouseEventArgs e)
{
Point position = e.GetPosition(this);
double x = position.X;
double y = position.Y;
double angle;
double radians;
radians = Math.Atan2(y, x);
angle = radians * (180 / Math.PI);
}
角度似乎不正确,永远不会得到0或90 180。三角法可以帮你做到这一点 因此,您需要使用反正切来实现这一点(位于System.Math.ATan) 您还需要考虑角度是pi/2(或90度)倍数的情况 您可以使用Atan2 只需在鼠标y坐标和圆心之间传递y作为增量,x也是如此。
请注意,结果是以辐射形式表示的。如果它是一个圆,并且相对于圆有X,Y,则可以通过半径-Y,半径-X,如果它是一个椭圆,则可以通过高度/2-Y,宽度/2-X。好的,mouseeventarg会公开函数“GetPosition”,该函数要求用户界面元素提供相对鼠标位置。这基本上就是你想要做的
private void ellipse1_MouseMove(object sender, MouseEventArgs e)
{
// This will get the mouse cursor relative to the upper left corner of your ellipse.
// Note that nothing will happen until you are actually inside of your ellipse.
Point curPoint = e.GetPosition(ellipse1);
// Assuming that your ellipse is actually a circle.
Point center = new Point(ellipse1.Width / 2, ellipse1.Height / 2);
// A bit of math to relate your mouse to the center...
Point relPoint = new Point(curPoint.X - center.X, curPoint.Y - center.Y);
// The fruit of your labor.
Console.WriteLine("({0}:{1})", relPoint.X, relPoint.Y);
}
从你的评论和其他帖子看来,既然你有了正确的信息,你可以自己处理实际的角度计算部分。就单位而言,WPF使用独立于设备的坐标系。因此半径为50的圆不一定是50像素。这完全取决于你的系统、屏幕分辨率等。这有点无聊,但如果你真的感兴趣的话,这会为你解释一些
e.GetPosition(this)返回的确切位置是什么?这是我问题的一部分,它是WPF标准的mousemove处理程序:)获取“this”的位置将给出包含处理程序的对象的位置,在您的情况下可能是一个窗口。如果您想要相对于引发事件的椭圆的位置,您可以使用e.GetPosition(sender),或者直接将其命名为e.GetPosition(ellipse1)。Atan2会自动执行您描述的检查,请参见上面的答复。@Felice Pollano,我不知道,很高兴知道。另外,你的回答也很好。谢谢,我知道,只是因为我手工做这些箱子时犯了很多错误;)如何获得X、Y和X。圆心和Y。WPF使用什么坐标系?坐标系并不重要,只需确保鼠标坐标和圆心坐标相同即可。公共点GetPosition(UIElement relativeTo),如果你将圆作为UIElement传递,它应该只传递两个坐标。我尝试查看我的代码更新,但角度似乎不正确。你认为呢?你必须从中心坐标减去你找到的坐标x,y:radius-y,radius-x.@FelicePollano您应该将该评论编辑到您的答案中,因为我认为这是一个完整的答案:)
private void ellipse1_MouseMove(object sender, MouseEventArgs e)
{
// This will get the mouse cursor relative to the upper left corner of your ellipse.
// Note that nothing will happen until you are actually inside of your ellipse.
Point curPoint = e.GetPosition(ellipse1);
// Assuming that your ellipse is actually a circle.
Point center = new Point(ellipse1.Width / 2, ellipse1.Height / 2);
// A bit of math to relate your mouse to the center...
Point relPoint = new Point(curPoint.X - center.X, curPoint.Y - center.Y);
// The fruit of your labor.
Console.WriteLine("({0}:{1})", relPoint.X, relPoint.Y);
}