C# DrawEllipse defining coordinates

By drawing 2 ellipses

Pen myPen = new Pen(Color.Black, 2);
Graphics g = e.Graphics;
g.DrawEllipse(myPen, 150, 70, 300, 300);
Pen myPen1 = new Pen(Color.Red, 2);
Graphics u = e.Graphics;
u.DrawEllipse(myPen1, 165, 85, 270, 270);

I want to find out by the MouseClick event whether the user got the cursor between them. I tried to take the value of x and y by pressing

int x = e.X; 
int y = e.Y;

But I don't understand what condition to use

Author: VladD, 2018-03-11

2 answers

You don't need to draw ellipses, but GraphicsPath with ellipse rendering:

using (var myPen1 = new Pen(Color.Black, 2))
using (var myPen2 = new Pen(Color.Red, 2))
{
    DrawPath(e.Graphics, myPen1, rectangle1);
    DrawPath(e.Graphics, myPen2, rectangle2);
}

private void DrawPath(Graphics g, Pen pen, Rectangle rectangle)
{
    using (var path = GetEllipsePath(rectangle))
    {
        g.DrawPath(pen, path);
    }
}

private GraphicsPath GetEllipsePath(Rectangle rectangle)
{
    var path = new GraphicsPath();
    path.AddEllipse(rectangle);
    return path;
}

, where rectangle1 and rectangle2 are the rectangles you need to describe the ellipse:

Rectangle rectangle1 = new Rectangle(150, 70, 300, 300);
Rectangle rectangle2 = new Rectangle(165, 85, 270, 270);

To determine whether a point belongs to an instance of GraphicsPath, we use the IsVisible method. Thus, the method that shows whether a certain point is located between the specified ellipses will look like this:

private bool IsPointBetweenEllipses(Point p)
{
    using (var path1 = GetEllipsePath(rectangle1))
    using (var path2 = GetEllipsePath(rectangle2))
    {
        return path1.IsVisible(p) ^ path2.IsVisible(p);
    }
}

PS. Almost all primitives from System.Drawing implement IDisposable. So don't forget them release.

 3
Author: Vlad, 2018-03-11 10:30:17

A variant of a point belonging to an ellipse through a mathematical definition a little theory

int a = 300;//большая полуось
int b = 300;//малая полуось
int x = 150, y = 70;
int f1f2 = sqrt(a*a-b*b)*2;//расстояние между фокусами
int f1 = x + a/2 - f1f2/2;
int f2 = x + a/2 + f1f2/2;
int fy = y + b/2;

if (diastance(e.X,e.Y,f1,fy) + diastance(e.X,e.Y,f1,fy) <= 2*a)
{
//точка в эллипсе
}

Distance method:

float diastance(int x1, int y1, int x2, int y2)
{
  int d1 = abs(x1-x2);
  int d2 = abs(y1-y2);
  return sqrt(d1*d1 + d2*d2);
}
 0
Author: dgzargo, 2018-03-11 09:46:05