5

I'm having troubles finding the classic 'Contains' method which returns if a point is within a rectangle, ellipse or some other object. These objects are in a canvas.

I've tried VisualTreeHelper.FindElementsInHostCoordinates but I can't find the way.

How can I do this?

2 Answers 2

13

This works for me. *(If you find it usefull please vote it!)

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

It's not quite so simple with C#.

First you need a GraphicsPath. Then initialise it which the shape that you want, for an ellipse use the method AddEllipse. Then use the IsVisible method to check if your point is contained within the shape. You can test for arbitrary shapes by using one of the various AddLine methods.

eg.

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);
1
  • I don't know why you can't find it. But it's definitely there. There are quite a few tutorials online about using GraphicsPath with silverlight eg. c-sharpcorner.com/uploadfile/mahesh/…
    – Dunes
    Commented Nov 8, 2012 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.