Mirror

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


Problem/Question/Abstract:

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

Answer:

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;
var
  L, I, J: Integer;

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

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

begin
  Result := False;
  L := Length(aList);
  if L = 0 then
    exit;
  J := L - 1;
  for I := 0 to L - 1 do
  begin
    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;
  end;
end;

<< Back to main page