如何使用path2d绘制多边形并查看某个点是否位于其区域内?

我试图使用带有path2d的多个顶点绘制任何类型的多边形形状,我想稍后使用java.awt.geom.Area查看确定点是否在其区域内

public static boolean is insideRegion(Region region, Coordinate coord){ Geopoint lastGeopoint = null; GeoPoint firstGeopoint = null; final Path2D boundary = new Path2D.Double(); for(GeoPoint geoponto : region.getGeoPoints()){ if(firstGeopoint == null) firstGeopoint = geoponto; if(lastGeopoint != null){ boundary.moveTo(lastGeopoint.getLatitude(),lastGeopoint.getLongitude()); boundary.lineTo(geoponto.getLatitude(),geoponto.getLongitude()); } lastGeopoint = geoponto; } boundary.moveTo(lastGeopoint.getLatitude(),lastGeopoint.getLongitude()); boundary.lineTo(firstGeopoint.getLatitude(),firstGeopoint.getLongitude()); final Area area = new Area(boundary); Point2D point = new Point2D.Double(coord.getLatitude(),coord.getLongitude()); if (area.contains(point)) { return true; } return false } 

所以我把这个非常快速的测试放在一起。

 public class Poly extends JPanel { private Path2D prettyPoly; public Poly() { prettyPoly = new Path2D.Double(); boolean isFirst = true; for (int points = 0; points < (int)Math.round(Math.random() * 100); points++) { double x = Math.random() * 300; double y = Math.random() * 300; if (isFirst) { prettyPoly.moveTo(x, y); isFirst = false; } else { prettyPoly.lineTo(x, y); } } prettyPoly.closePath(); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Point p = e.getPoint(); System.out.println(prettyPoly.contains(p)); repaint(); } }); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.draw(prettyPoly); g2d.dispose(); } } 

这会在随机位置生成随机数量的点。

然后使用鼠标单击确定鼠标单击是否落在该形状内

更新

(注意,我将g2d.draw更改为g2d.fill ,以便更容易看到内容区域)

PrettyPoly

请注意,红色的所有内容都返回“true”,其他所有内容都返回“false”...