DelphiFAQ Home Search:

Is a point inside a given polygon?

 

comments2 comments. Current rating: 5 stars (2 votes). Leave comments and/ or rate it.

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;
You don't like the formatting? Check out SourceCoder then!

Comments:

2006-01-27, 05:54:52
anonymous from United Kingdom  
rating
2007-01-06, 13:40:55
[hidden] from Israel  
rating
that's really great

Delphi is just my hobby, and i'm not a programmer.
however, i want to make something that uses polygons that are made randomly.
can you teach us how to make random shaped polygons?

thanks for your help (and sorry for my english)

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Los Angeles, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.