5

我很难找到经典的“包含”方法,如果一个点在矩形、椭圆或其他对象内,该方法会返回。这些对象位于画布中。

我试过 VisualTreeHelper.FindElementsInHostCoordinates 但我找不到路。

我怎样才能做到这一点?

4

2 回答 2

13

这对我有用。*(如果觉得有用请投票!)

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;
        }
于 2012-11-08T10:10:18.757 回答
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);
于 2012-11-08T08:46:35.293 回答