Determine whether a point lies inside a polygon in C#

The GraphicsPath class provides an easy method for determining whether a point lies within a polygon. The following code wraps up a call to a GraphicsPath object's IsVisible method.

// Return true if the point is inside the polygon.
private bool PointIsInPolygon(Point[] polygon, Point target_point)
{
// Make a GraphicsPath containing the polygon.
GraphicsPath path = new GraphicsPath();
path.AddPolygon(polygon);

// See if the point is inside the path.
return path.IsVisible(target_point);
}

This code creates a GraphicsPath and adds the polygon to it. It then calls its IsVisible method to see whether the point lies within the polygon.

The program's MouseMove event handler uses PointIsInPolygon to change the form's cursor to a cross hair when the mouse is over the polygon.

// Set the cursor depending on whether the mouse is over the polygon.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Cursor new_cursor;
if (PointIsInPolygon(Points, e.Location))
{
new_cursor = Cursors.Cross;
}
else
{
new_cursor = Cursors.Default;
}

// Update the cursor.
if (this.Cursor != new_cursor) this.Cursor = new_cursor;
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.