2011-01-24 98 views
2

mousemove时我有一个圆圈我可以得到e.GetPosition(this)。但如何以编程方式获取相对于圆心的角度?获取WPF中鼠标位置相对于圆心的最简单方法

我在网上看到了一些带有XAML绑定的示例时钟。这不是我想要的,我想从鼠标位置相对于圆心获取角度值。

这是我的尝试:

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

+0

e.GetPosition(this)究竟返回什么? – 2011-01-24 16:08:25

+0

那么这是我的问题的一部分,它是WPF标准mousemove处理程序:) – user310291 2011-01-24 16:26:40

+0

获取'this'的位置会给你包含处理程序的对象的位置,可能是您的情况中的一个窗口。如果您想要相对于引发事件的椭圆的位置,或者直接命名它,即e.GetPosition(ellipse1),则可以使用e.GetPosition(sender)。 – 2011-01-24 16:55:56

回答

2

好的,MouseEventArgs公开了函数'GetPosition',它要求一个UI元素,它会给你鼠标的相对位置。这基本上是你想要做的。

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像素。这一切都取决于你的系统,屏幕分辨率等等。这一切都很无聊,但如果你真的感兴趣,这将解释一些它。

http://msdn.microsoft.com/en-us/library/ms748373.aspx

1

三角可以为你做到这一点。

所以你会想使用弧切线来做到这一点(这是发现在System.Math.ATan)。

您还需要考虑角度是pi/2(或90度)倍数的情况。

+0

Atan2会自动执行您描述的检查,请参阅上面的回复。 – 2011-01-24 16:12:41

3

您可以使用Atan2 http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx

public static double Atan2(
    double y, 
    double x 
) 

只是将y传递为您的鼠标y坐标和圆心的差值,对于x也是如此。 注意结果用radiant表示,如果它是一个圆形,并且相对于可以传递radius-y,radius-x的圆的X,Y,如果它是一个椭圆,则可以传递高度/ 2-y ,宽度/ 2-x。