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

时间:2012-08-28 03:46:33

标签: java area path-2d

我试图使用带有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
}

1 个答案:

答案 0 :(得分:8)

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

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”......