如何使用Path2D绘制一个多边形并判断一个点是否在其内部?

4

我正在尝试使用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
}

我的代码中有一部分在编辑器上。 - B. TIger
因为Path2Contains会判断点是否在图形的线上,但不包括其内容。 - B. TIger
是的,形状构成了一个封闭区域。 - B. TIger
3
如果你在使用我发布的答案,为什么不接受它呢? - obataku
@B.TIger 我的测试结果与此不同。只要我在多边形“内部”点击任何位置,Path2D.contains 就会返回 true。 - MadProgrammer
显示剩余3条评论
1个回答

10

所以我组织了这个非常快速的测试。

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


谢谢你,但问题是我已经收到了画多边形的点,现在我需要计算线之间的路径,并判断一个确定的点是否在该区域内。 - B. TIger
@B.Tiger 是的,鼠标点击就是这样。随机点生成器只是一个测试,用来演示它的工作原理。 - MadProgrammer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接