如何使用path2d绘制多边形并查看某个点是否位于其区域内? [英] How can I draw a polygon using path2d and see if a point is within it's area?
问题描述
我试图使用带有path2d的多个顶点绘制任何类型的多边形形状,我想稍后使用java.awt.geom.Area
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
}
推荐答案
所以我把这个非常快速的测试放在一起。
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
更新
(注意,我将 g2d.draw
更改为 g2d.fill
,以便更容易看到内容区域)
(Note, I changed the g2d.draw
to g2d.fill
to make it easier to see the content area)
注意,红色的所有内容都返回true,其他所有内容都返回false...
Note, everything in red returns "true", everything else returns "false"...
这篇关于如何使用path2d绘制多边形并查看某个点是否位于其区域内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!