2012-11-08 49 views
3

我遇到了麻煩找到經典的'包含'方法,如果它是在一個矩形,橢圓或其他對象內的點,返回。這些對象位於畫布中。如何確定點是否在橢圓內?

我試過VisualTreeHelper.FindElementsInHostCoordinates,但是我找不到方法。

確有人幫我嗎?

在此先感謝!

回答

6

這對我有用。 *(如果你覺得有用請投票吧!)

http://my.safaribooksonline.com/book/programming/csharp/9780672331985/graphics-with-windows-forms-and-gdiplus/ch17lev1sec22

public bool Contains(Ellipse Ellipse, Point location) 
     { 
      Point center = new Point(
        Canvas.GetLeft(Ellipse) + (Ellipse.Width/2), 
        Canvas.GetTop(Ellipse) + (Ellipse.Height/2)); 

      double _xRadius = Ellipse.Width/2; 
      double _yRadius = Ellipse.Height/2; 


      if (_xRadius <= 0.0 || _yRadius <= 0.0) 
       return false; 
      /* This is a more general form of the circle equation 
      * 
      * X^2/a^2 + Y^2/b^2 <= 1 
      */ 

      Point normalized = new Point(location.X - center.X, 
             location.Y - center.Y); 

      return ((double)(normalized.X * normalized.X) 
        /(_xRadius * _xRadius)) + ((double)(normalized.Y * normalized.Y)/(_yRadius * _yRadius)) 
       <= 1.0; 
     } 
3

C#並不是那麼簡單。

首先你需要一個GraphicsPath。然後將其初始化爲您想要的形狀,對於橢圓使用方法AddEllipse。然後使用IsVisible方法檢查您的點是否包含在形狀中。您可以使用各種AddLine方法之一來測試任意形狀。

例如。

Rectangle myEllipse = new Rectangle(20, 20, 100, 50); 
// use the bounding box of your ellipse instead 
GraphicsPath myPath = new GraphicsPath(); 
myPath.AddEllipse(myEllipse); 
bool pointWithinEllipse = myPath.IsVisible(40,30); 
+0

它看起來真的很辛苦:/ – ymutlu

+0

我無法找到的GraphicsPath ... – MirlvsMaximvs

+0

我不知道爲什麼你可以」找到它。但它絕對存在。網上有很多關於如何使用帶有silverlight的'GraphicsPath'的教程,例如。 http://www.c-sharpcorner.com/uploadfile/mahesh/graphics-path-in-silverlight/ – Dunes