How to detect if a point lies within a polygon (Views: 100)


Can anyone help me with detecting if the screen coordinates that a user has clicked on lies within a defined polygon?


The code below is from Wm. Randolph Franklin with some minor modifications for speed. It returns 1 for strictly interior points, 0 for strictly exterior, and 0 or 1 for points on the boundary.

function PointInPolygonTest(x, y: Integer; aList: array of TPoint): Boolean;
  L, I, J: Integer;

  function xp(aVal: Integer): Integer;
    Result := PPoint(@aList[aVal]).X;

  function yp(aVal: Integer): Integer;
    Result := PPoint(@aList[aVal]).Y;

  Result := False;
  L := Length(aList);
  if L = 0 then
  J := L - 1;
  for I := 0 to L - 1 do
    if ((((yp(I) <= y) and (y < yp(J))) or ((yp(J) <= y) and (y < yp(I)))) and
      (x < (xp(J) - xp(I)) * (y - yp(I)) / (yp(J) - yp(I)) + xp(I))) then
      Result := not Result;
    J := I;

<< Back to main page