如何确定一个点是否在椭圆内?

5

我遇到了一些麻烦,无法找到经典的“Contains”方法,该方法返回一个点是否在矩形、椭圆或其他对象内。这些对象在画布上。

我已经尝试使用VisualTreeHelper.FindElementsInHostCoordinates,但我找不到方法。

我该如何做?

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;
        }

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);

我不知道为什么你找不到它。但是它肯定在那里。关于在Silverlight中使用GraphicsPath,有很多在线教程,例如http://www.c-sharpcorner.com/uploadfile/mahesh/graphics-path-in-silverlight/。 - Dunes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接