我怎样才能使用path2d绘制多边形,并查看是否有一点是它的区域内?(How can I draw

2019-09-21 18:22发布

I,M企图拉拢使用与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
}

Answer 1:

所以我放在一起这真的快速测试。

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.drawg2d.fill ,使其更容易看到的内容区)

注意,一切都在红色返回“真”,一切返回“false” ...



文章来源: How can I draw a polygon using path2d and see if a point is within it's area?