Identify if a point is within a polygon?
custom-controls, delphi, delphi-xe2, polygon
Solution
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;
Problem
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; ```