Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify if a point is within a polygon?

I'm making a custom control in Delphi (inherited from TCustomControl) which consists of a number of polygon list items (irregular shapes). I need to implement mouse events per item, but first I need to be able to detect if the mouse position is within a given polygon (array of TPoint). I am catching the Hit Test message (WM_NCHITTEST) and this is where I will need to do this validation. I have a number of polygons, I will do a loop through each polygon item and perform this check to see if the mouse's X/Y position is within this polygon.

procedure TMyControl.WMNCHitTest(var Message: TWMNCHitTest);
var
  P: TPoint; //X/Y of Mouse
  Poly: TPoints; //array of TPoint
  X: Integer; //iterator
  I: TMyListItem; //my custom list item
begin
  P.X:= Message.XPos;
  P.Y:= Message.YPos;
  for X := 0 to Items.Count - 1 do begin
    I:= Items[X]; //acquire my custom list item by index
    Poly:= I.Points; //acquire polygon points

    //Check if Point (P) is within Polygon (Poly)...?

  end;
end;
like image 594
Jerry Dodge Avatar asked May 10 '12 19:05

Jerry Dodge


People also ask

How do you check if a point is inside a polygon in Python?

How to check if a point is inside a polygon in Python. To perform a Point in Polygon (PIP) query in Python, we can resort to the Shapely library's functions . within(), to check if a point is within a polygon, or . contains(), to check if a polygon contains a point.

Is a point inside or outside a polygon?

If the number of times this ray intersects the line segments making up the polygon is even then the point is outside the polygon. Whereas if the number of intersections is odd then the point (xp,yp) lies inside the polygon.

How do you check if a point is inside a polyhedron?

The idea is rather simple. Given that specific point, compute a sum of signed solid angles of all faces of the polyhedron as viewed from that point. If the point is outside, that sum gotta be zero.


1 Answers

You can use PtInRegion:

function PointInPolygon(Point: TPoint; const Polygon: array of TPoint): Boolean;
var
  rgn: HRGN;
begin
  rgn := CreatePolygonRgn(Polygon[0], Length(Polygon), WINDING);
  Result := PtInRegion(rgn, Point.X, Point.Y);
  DeleteObject(rgn);
end;
like image 153
David Heffernan Avatar answered Sep 27 '22 22:09

David Heffernan