使用 Geotools JMapFrame 显示图例

display legend with Geotools JMapFrame

有人可以提供一些关于如何在 Geotools 的 JMapFrame 中显示 shapefile 的图例的提示吗?我已经为 shapefile 创建了样式,我需要一种方法来告诉用户样式是如何定义的,这就是图例的需要。

有一个包裹org.geotools.legend。但是不知道怎么用。

谢谢!

您需要遍历 Styles FeatureTypeStyless Rules Symbolizers 并为每个人绘制一个具有代表性的特征。类似于:

private void drawLegend(BufferedImage img, Rule r) {
    for (Symbolizer sym : r.symbolizers()) {
      SimpleFeature feature = null;
      if (sym instanceof LineSymbolizer) {
        LineString line = drawer.line(new int[] { 1, 1, 10, 20, 20, 20 });
        feature = drawer.feature(line);
      } else if(sym instanceof PolygonSymbolizer) {
        Polygon  p = drawer.polygon(new int[] { 1, 1, 1, 18, 18, 18, 18, 1, 1,1 });
        feature = drawer.feature(p);
      } else if(sym instanceof PointSymbolizer || sym instanceof TextSymbolizer) {
        Point p = drawer.point(10, 10);
        feature = drawer.feature(p);
      } 
      if(feature == null)
        continue;
      drawer.drawDirect(img, feature, r);
      Graphics2D gr = img.createGraphics();
      gr.setColor(Color.BLACK);
      if (r.getDescription() != null && r.getDescription().getTitle() != null) {
        gr.drawString(r.getDescription().getTitle().toString(), 20, 18);
      }
    }
  }

然后您可以将这些图像绘制到 JPanel 或地图上。

有关完整的示例,请参阅 GeoServer 如何创建对 getLegendGraphic request 的响应。