【问题标题】:How can I draw a polygon using path2d and see if a point is within it's area?如何使用 path2d 绘制多边形并查看一个点是否在其区域内?
【发布时间】:2012-08-22 13:28:06
【问题描述】:

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

【问题讨论】:

  • 我的部分代码在编辑中
  • 为什么不用Path2D#contains() 而不是Area#contains()
  • 生成的形状是否构成封闭区域??
  • 因为 Path2Contains 如果点在图形的线上,不包括它的内容,就会给出提示
  • @B.TIger 如果您使用我发布的答案,您为什么不接受?

标签: java area path-2d


【解决方案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.draw改成了g2d.fill,方便看内容区)

注意,红色的一切都返回“真”,其他一切都返回“假”...

【讨论】:

  • 谢谢,但问题是我已经收到了在方法上绘制多边形的点,我必须计算线之间的路径,看看一个确定的点是否在一个区域内
  • @B.TIger 是的,鼠标点击就是这样做的。随机点生成器只是一个测试来演示它是如何工作的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
相关资源
最近更新 更多