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?
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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With