Mega Code Archive

 
Categories / Delphi / Examples
 

Is a point inside a given polygon

Question: It is of interest to determin if a point is within a given polygon. My polygon is represented as an array of TPoints. Answer: A quick way to do this is to use the Windows API function PtInRegion. If not already avalaible, call CreatePolygonRgn() to create a region and pass the region's handle to PtInRegion(). Don't forget to free Windows' region handle afterwards. A neat trick is to use the Length() function to obtain the number of points in the polygon. // PointInPolygon() function by Andreas Filsinger function PointInPolygon (const x,y : integer; aPolygon: array of TPoint): boolean; var PolyHandle: hRgn; begin PolyHandle := CreatePolygonRgn(aPolygon[0], Length(aPolygon), Winding); result := PtInRegion(PolyHandle,X,Y); DeleteObject(PolyHandle); end;