[英]How can I draw a polygon using path2d and see if a point is within it's area?
我試圖使用帶有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
}
所以我把這個非常快速的測試放在一起。
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
,以便更容易查看內容區域)
請注意,紅色的所有內容都返回“true”,其他所有內容都返回“false”...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.