Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I draw a polygon using path2d and see if a point is within it's area?

Tags:

java

area

path-2d

I,m trying to draw a polygon shape of any kind using multiple vertices with path2d and I want to later on see if a determinate point is within its area using 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
}
like image 872
B. TIger Avatar asked Dec 26 '22 18:12

B. TIger


1 Answers

So I put together this really quick test.

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();

    }
}

This generates a random number of points at random locations.

It then uses the mouse click to determine if the mouse click falls within that shape

UPDATED

(Note, I changed the g2d.draw to g2d.fill to make it easier to see the content area)

PrettyPoly

Note, everything in red returns "true", everything else returns "false"...

like image 196
MadProgrammer Avatar answered Jan 17 '23 16:01

MadProgrammer