/[schmitzm]/trunk/src/skrueger/geotools/LegendIconFeatureRenderer.java
ViewVC logotype

Diff of /trunk/src/skrueger/geotools/LegendIconFeatureRenderer.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 244 by alfonx, Wed Jul 29 09:33:33 2009 UTC revision 1270 by alfonx, Sun Nov 14 00:25:52 2010 UTC
# Line 2  Line 2 
2   * Copyright (c) 2009 Martin O. J. Schmitz.   * Copyright (c) 2009 Martin O. J. Schmitz.
3   *   *
4   * This file is part of the SCHMITZM library - a collection of utility   * This file is part of the SCHMITZM library - a collection of utility
5   * classes based on Java 1.6, focussing (not only) on Java Swing   * classes based on Java 1.6, focusing (not only) on Java Swing
6   * and the Geotools library.   * and the Geotools library.
7   *   *
8   * The SCHMITZM project is hosted at:   * The SCHMITZM project is hosted at:
# Line 25  Line 25 
25   *   *
26   * Contributors:   * Contributors:
27   *     Martin O. J. Schmitz - initial API and implementation   *     Martin O. J. Schmitz - initial API and implementation
28   *     Stefan A. Krüger - additional utility classes   *     Stefan A. Tzeggai - additional utility classes
29   ******************************************************************************/   ******************************************************************************/
30  /**  /**
31   Copyright 2008 Stefan Alfons Krüger and parts from some Geotools code     Copyright 2008 Stefan Alfons Tzeggai and parts from some Geotools code  
32    
33   atlas-framework - This file is part of the Atlas Framework   atlas-framework - This file is part of the Atlas Framework
34    
35   This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.   This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
# Line 42  Line 42 
42   **/   **/
43  package skrueger.geotools;  package skrueger.geotools;
44    
 import java.awt.Canvas;  
45  import java.awt.Color;  import java.awt.Color;
46  import java.awt.Dimension;  import java.awt.Dimension;
 import java.awt.FontMetrics;  
 import java.awt.Graphics;  
47  import java.awt.Graphics2D;  import java.awt.Graphics2D;
48  import java.awt.RenderingHints;  import java.awt.RenderingHints;
49  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
 import java.awt.image.ImageObserver;  
 import java.util.ArrayList;  
 import java.util.List;  
   
 import javax.swing.tree.DefaultTreeCellRenderer;  
50    
51  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
52  import org.geotools.factory.GeoTools;  import org.geotools.factory.GeoTools;
53  import org.geotools.factory.Hints;  import org.geotools.factory.Hints;
 import org.geotools.feature.AttributeType;  
 import org.geotools.feature.Feature;  
 import org.geotools.feature.FeatureType;  
 import org.geotools.feature.IllegalAttributeException;  
54  import org.geotools.geometry.jts.LiteShape2;  import org.geotools.geometry.jts.LiteShape2;
55  import org.geotools.renderer.lite.StyledShapePainter;  import org.geotools.renderer.lite.StyledShapePainter;
56  import org.geotools.renderer.style.SLDStyleFactory;  import org.geotools.renderer.style.SLDStyleFactory;
# Line 76  import org.geotools.styling.Style; Line 64  import org.geotools.styling.Style;
64  import org.geotools.styling.Symbolizer;  import org.geotools.styling.Symbolizer;
65  import org.geotools.styling.TextSymbolizer;  import org.geotools.styling.TextSymbolizer;
66  import org.geotools.util.NumberRange;  import org.geotools.util.NumberRange;
67    import org.opengis.feature.IllegalAttributeException;
68    import org.opengis.feature.simple.SimpleFeature;
69    import org.opengis.feature.simple.SimpleFeatureType;
70    import org.opengis.feature.type.AttributeDescriptor;
71    
72  import schmitzm.geotools.feature.FeatureUtil;  import schmitzm.geotools.feature.FeatureUtil;
73    
# Line 89  import com.vividsolutions.jts.geom.Polyg Line 81  import com.vividsolutions.jts.geom.Polyg
81   * Based on geoserver!   * Based on geoserver!
82   * <hr>   * <hr>
83   * <b>Changes by <a href="mailto:[email protected]">Martin Schmitz</a></b>   * <b>Changes by <a href="mailto:[email protected]">Martin Schmitz</a></b>
  * <br>  
  * <ul>  
84   * <li>07.02.2008:<br>   * <li>07.02.2008:<br>
85   * Determining the default values of a {@link FeatureType} by   * Determining the default values of a {@link SimpleFeatureType} by
86   * {@link FeatureUtil#getDefaultAttributeValues(FeatureType)} instead of using   * {@link FeatureUtil#getDefaultAttributeValues(SimpleFeatureType)} instead of
87   * {@link AttributeType#createDefaultValue()} directly, because the latter   * using {@link AttributeDescriptor#createDefaultValue()} directly, because the
88   * returns {@code null} even though the attribut is not nillable.</li>   * latter returns {@code null} even though the attribut is not nillable.</li>
89   * </ul>   * </ul>
90   *   *
91   * @author Stefan Alfons Krüger   * @author Stefan Alfons Tzeggai
92   */   */
93  public class LegendIconFeatureRenderer extends DefaultTreeCellRenderer {  public class LegendIconFeatureRenderer {
94          private static final Dimension SIZE = new Dimension(30,20);          // private static final Dimension SIZE = new Dimension(30,20);
95    
96          Logger LOGGER = Logger.getLogger(LegendIconFeatureRenderer.class);          Logger LOGGER = Logger.getLogger(LegendIconFeatureRenderer.class);
97    
# Line 114  public class LegendIconFeatureRenderer e Line 104  public class LegendIconFeatureRenderer e
104          final static LegendIconFeatureRenderer instance = new LegendIconFeatureRenderer();          final static LegendIconFeatureRenderer instance = new LegendIconFeatureRenderer();
105    
106          public static LegendIconFeatureRenderer getInstance() {          public static LegendIconFeatureRenderer getInstance() {
107                  // In GT 2.4.5 it we have to create a new one all the time!                  return instance;
                 return new LegendIconFeatureRenderer();  
 //               return instance;  
108          }          }
109    
         /** The image produced at <code>produceLegendGraphic</code> */  
         private BufferedImage legendGraphic;  
   
110          /**          /**
111           * used to create sample point shapes with LiteShape (not lines nor           * used to create sample point shapes with LiteShape (not lines nor
112           * polygons)           * polygons)
113           */           */
114          private static final GeometryFactory geomFac = new GeometryFactory();          private static final GeometryFactory geomFac = FeatureUtil.GEOMETRY_FACTORY;
115    
116          /** padding percentage factor at both sides of the legend. */          /** padding percentage factor at both sides of the legend. */
117          private static final float hpaddingFactor = 0.11f; // was 0.15          private static final float hpaddingFactor = 0.11f; // was 0.15
# Line 135  public class LegendIconFeatureRenderer e Line 120  public class LegendIconFeatureRenderer e
120          private static final float vpaddingFactor = 0.08f; // was 0.15          private static final float vpaddingFactor = 0.08f; // was 0.15
121    
122          /**          /**
          * Image observer to help in creating the stack like legend graphic from the  
          * images created for each rule  
          */  
         private static final ImageObserver imgObs = new Canvas();  
   
         /**  
123           * Just a holder to avoid creating many polygon shapes from inside           * Just a holder to avoid creating many polygon shapes from inside
124           * <code>getSampleShape()</code>           * <code>getSampleShape()</code>
125           */           */
# Line 161  public class LegendIconFeatureRenderer e Line 140  public class LegendIconFeatureRenderer e
140          private Hints hints;          private Hints hints;
141    
142          /**          /**
143           * Returns a <code>java.awt.Shape</code> appropiate to render a legend           * Returns a <code>java.awt.Shape</code> appropriate to render a legend
144           * graphic given the symbolizer type and the legend dimensions.           * graphic given the symbolizer type and the legend dimensions.
145           *           *
146           * @param symbolizer           * @param symbolizer
# Line 175  public class LegendIconFeatureRenderer e Line 154  public class LegendIconFeatureRenderer e
154           *         symbolizer, wether it is a LineSymbolizer, a PolygonSymbolizer,           *         symbolizer, wether it is a LineSymbolizer, a PolygonSymbolizer,
155           *         or a Point ot Text Symbolizer           *         or a Point ot Text Symbolizer
156           *           *
          * @throws IllegalArgumentException  
          *             if an unknown symbolizer impl was passed in.  
157           */           */
158          private LiteShape2 getSampleShape(Symbolizer symbolizer, int legendWidth,          private LiteShape2 getSampleShape(Symbolizer symbolizer, int legendWidth,
159                          int legendHeight) {                          int legendHeight) {
# Line 228  public class LegendIconFeatureRenderer e Line 205  public class LegendIconFeatureRenderer e
205                                                  legendHeight / 2);                                                  legendHeight / 2);
206    
207                                  try {                                  try {
208                                          this.samplePoint = new LiteShape2(geomFac                                          this.samplePoint = new LiteShape2(
209                                                          .createPoint(coord), null, null, false);                                                          geomFac.createPoint(coord), null, null, false);
210                                  } catch (Exception e) {                                  } catch (Exception e) {
211                                          this.samplePoint = null;                                          this.samplePoint = null;
212                                  }                                  }
# Line 240  public class LegendIconFeatureRenderer e Line 217  public class LegendIconFeatureRenderer e
217                          throw new IllegalArgumentException("Unknown symbolizer: "                          throw new IllegalArgumentException("Unknown symbolizer: "
218                                          + symbolizer);                                          + symbolizer);
219                  }                  }
   
220                  return sampleShape;                  return sampleShape;
221          }          }
222    
223          /**          /**
          * Puts a BufferedImage into this.legendGraphic  
          */  
         public void produceLegendGraphic(FeatureType featureType, Style gt2Style,  
                         Rule[] applicableRules) {  
   
                 // final FeatureTypeStyle[] ftStyles = gt2Style.getFeatureTypeStyles();  
   
                 // if (request.getRule() != null) {  
                 // applicableRules = new Rule[] { request.getRule() };  
                 // } else {  
                 // applicableRules = getApplicableRules(ftStyles, scaleDenominator);  
                 // }  
   
                 final int ruleCount = applicableRules.length;  
   
                 /**  
                  * A legend graphic is produced for each applicable rule. They're being  
                  * holded here until the process is done and then painted on a "stack"  
                  * like legend.  
                  */  
                 final List<BufferedImage> legendsStack = new ArrayList<BufferedImage>(  
                                 ruleCount);  
   
                 for (int i = 0; i < ruleCount; i++) {  
                         BufferedImage image = createImageForRule(applicableRules[i],  
                                         featureType, SIZE);  
                         legendsStack.add(image);  
                 }  
   
                 // this.legendGraphic =  
                 // scaleImage(mergeLegends(legendsStack,applicableRules), request);  
                 this.legendGraphic = mergeLegends(legendsStack, applicableRules);  
         }  
   
         /**  
          * Recieves a list of <code>BufferedImages</code> and produces a new one  
          * which holds all the images in <code>imageStack</code> one above the  
          * other.  
          *  
          * @param imageStack  
          *            the list of BufferedImages, one for each applicable Rule  
          * @param rules  
          *            The applicable rules, one for each image in the stack  
          * @param request  
          *            The request.  
          *  
          * @return the stack image with all the images on the argument list.  
          *  
          * @throws IllegalArgumentException  
          *             if the list is empty  
          */  
         private static BufferedImage mergeLegends(List<BufferedImage> imageStack,  
                         Rule[] rules) {  
                 if (imageStack.size() == 0) {  
                         throw new IllegalArgumentException("No legend graphics passed");  
                 }  
   
                 BufferedImage finalLegend = null;  
   
                 if (imageStack.size() == 1) {  
                         finalLegend = (BufferedImage) imageStack.get(0);  
                 } else {  
                         final int imgCount = imageStack.size();  
                         final String[] labels = new String[imgCount];  
   
                         BufferedImage img = ((BufferedImage) imageStack.get(0));  
                         FontMetrics fontMetrics = img.getGraphics().getFontMetrics();  
   
                         final int rowHeight = Math.max(fontMetrics.getHeight(), img  
                                         .getHeight());  
   
                         // calculate the total dimensions of the image  
                         int totalHeight = rowHeight * imgCount;  
                         int totalWidth = 0;  
   
                         for (int i = 0; i < imgCount; i++) {  
                                 img = (BufferedImage) imageStack.get(i);  
   
                                 Rule rule = rules[i];  
   
                                 // does this rule have a label  
                                 labels[i] = rule.getTitle();  
   
                                 if (labels[i] == null) {  
                                         labels[i] = rule.getName();  
                                 }  
   
                                 int w = img.getWidth();  
   
                                 if (labels[i] != null) {  
                                         Graphics g = img.getGraphics();  
                                         w += g.getFontMetrics().stringWidth(labels[i]);  
                                 }  
   
                                 totalWidth = Math.max(w, totalWidth);  
                         }  
   
                         // create the final image  
                         finalLegend = new BufferedImage(totalWidth, totalHeight,  
                                         BufferedImage.TYPE_INT_ARGB);  
   
                         Graphics2D finalGraphics = finalLegend.createGraphics();  
   
                         finalGraphics.setColor(Color.white);  
                         finalGraphics.fillRect(0, 0, totalWidth, totalHeight);  
   
                         int h = 0;  
   
                         for (int i = 0; i < imgCount; i++) {  
                                 img = (BufferedImage) imageStack.get(i);  
   
                                 // draw the image  
                                 int y = h;  
   
                                 if (img.getHeight() < rowHeight) {  
                                         // move the image to the center of the row  
                                         y += (int) ((rowHeight - img.getHeight()) / 2d);  
                                 }  
   
                                 finalGraphics.drawImage(img, 0, y, imgObs);  
   
                                 // draw the label  
                                 if (labels[i] != null) {  
                                         finalGraphics.setColor(Color.BLACK);  
   
                                         y = (h + rowHeight) - fontMetrics.getDescent();  
   
                                         if (fontMetrics.getHeight() < rowHeight) {  
                                                 // move the baseline to the center of the row  
                                                 y -= (int) ((rowHeight - fontMetrics.getHeight()) / 2d);  
                                         }  
   
                                         finalGraphics.drawString(labels[i], img.getWidth(), y);  
                                 }  
   
                                 h += rowHeight;  
                         }  
                 }  
   
                 return finalLegend;  
         }  
   
         /**  
          * DOCUMENT ME!  
          *  
          * @return  
          *  
          * @throws IllegalStateException  
          *             DOCUMENT ME!  
          */  
         public BufferedImage getLegendGraphic() {  
                 if (this.legendGraphic == null) {  
                         throw new IllegalStateException();  
                 }  
                 return this.legendGraphic;  
         }  
   
         // /**  
         // * Paints a little rectangle in the color defined by the  
         // * {@link ColorMapEntry}  
         // *  
         // * unused  
         // *  
         // * @param cme  
         // * {@link ColorMapEntry}  
         // * @param cm  
         // * {@link ColorMap} to determine type (VALUES, INTERVALL )  
         // * @param iconWidth  
         // * Size of the rectangle  
         // * @param iconHeight  
         // * Size of the rectangle  
         // * @return {@link ImageIcon} of that color, maybe with a white border  
         // * @author Stefan Alfons Krüger  
         // */  
         // public static ImageIcon createImageForColorMapEntry(ColorMapEntry cme,  
         // ColorMap cm, Integer iconWidth, Integer iconHeight) {  
         //  
         // BufferedImage imageForRule = new BufferedImage(iconWidth, iconHeight,  
         // BufferedImage.TYPE_INT_ARGB);  
         //  
         // final Color color = StylingUtil.getColorFromColorMapEntry(cme);  
         //  
         // // Paint a block  
         // for (int x = 0; x < iconWidth; x++) {  
         // for (int y = 0; y < iconHeight; y++) {  
         // int rgb = color.getRGB();  
         // int rand = 2;  
         //  
         // // Paint a white border if the type is VALUES  
         // if ((x < rand) || (x > iconWidth - rand) || (y < rand)  
         // || (y > iconHeight - rand)) {  
         // if (cm.getType() == ColorMap.TYPE_VALUES) {  
         // rgb = Color.white.getRGB();  
         // }  
         // }  
         // imageForRule.setRGB(x, y, rgb);  
         // }  
         // }  
         // return new ImageIcon(imageForRule);  
         // }  
   
         /**  
224           * Creates a little BufferedImage that presents the Style/Symbols used by           * Creates a little BufferedImage that presents the Style/Symbols used by
225           * the {@link MapLegend} to show a legend for the {@link FeatureType}           * the {@link MapLegend} to show a legend for the {@link SimpleFeatureType}
226           *           *
227           * @param rule           * @param rule
228           *            {@link Rule} that provides the text and the style to present           *            {@link Rule} that provides the text and the style to present
229           * @param featureType           * @param featureType
230           *            Schema that describes the kind of the sample {@link Feature}           *            Schema that describes the kind of the sample
231           *            that will be rendered with the {@link Style}           *            {@link SimpleFeature} that will be rendered with the
232             *            {@link Style}
233           * @param bg           * @param bg
234           *            Background {@link Color} or <code>null</code>           *            Background {@link Color} or <code>null</code>
235           *           *
236           * @throws IllegalAttributeException           * @throws IllegalAttributeException
237           */           */
238          public BufferedImage createImageForRule(Rule rule, FeatureType featureType,          public BufferedImage createImageForRule(Rule rule,
239                          Dimension size, Color bg) {                          SimpleFeatureType featureType, Dimension size, Color bg) {
240    
241                  Symbolizer[] symbolizers = rule.getSymbolizers();                  Symbolizer[] symbolizers = rule.getSymbolizers();
242    
# Line 471  public class LegendIconFeatureRenderer e Line 246  public class LegendIconFeatureRenderer e
246    
247                  if (bg != null) {                  if (bg != null) {
248                          // ****************************************************************************                          // ****************************************************************************
249                          // The following lines define the backgroup color for the rendered                          // The following lines define the background color for the rendered
250                          // images                          // images
251                          // ****************************************************************************                          // ****************************************************************************
252                          graphics.setBackground(bg);                          graphics.setBackground(bg);
# Line 482  public class LegendIconFeatureRenderer e Line 257  public class LegendIconFeatureRenderer e
257                  // Enable anti-aliasing for the legend symbols                  // Enable anti-aliasing for the legend symbols
258                  graphics.setRenderingHints(getHints());                  graphics.setRenderingHints(getHints());
259    
260                  // TODO scaleDenominator = 100000000000000000000000000000d; Was ist das                  final NumberRange<Integer> scaleRange = NumberRange.create(
261                  // fuer ein Quatsch?                                  Integer.MAX_VALUE, Integer.MAX_VALUE);
                 final double scaleDenominator = 100000000000000000000000000000d;  
                 final NumberRange scaleRange = new NumberRange(scaleDenominator,  
                                 scaleDenominator);  
262    
263                  try {                  try {
264    
# Line 494  public class LegendIconFeatureRenderer e Line 266  public class LegendIconFeatureRenderer e
266                                  Symbolizer symbolizer = symbolizers[sIdx];                                  Symbolizer symbolizer = symbolizers[sIdx];
267    
268                                  if (symbolizer instanceof TextSymbolizer) {                                  if (symbolizer instanceof TextSymbolizer) {
                                         LOGGER  
                                                         .warn("createImageForRule for a TextSymbolizer. Sure we want that?");  
269                                          continue;                                          continue;
270                                  }                                  }
271    
# Line 504  public class LegendIconFeatureRenderer e Line 274  public class LegendIconFeatureRenderer e
274                                  // RasterSymbolizers..");                                  // RasterSymbolizers..");
275                                  // }                                  // }
276                                  // else                                  // else
277                                  final Feature sampleFeature = FeatureUtil.createSampleFeature(featureType);                                  final SimpleFeature sampleFeature = FeatureUtil
278                                                    .createSampleFeature(featureType);
279    
280                                    if (sampleFeature == null)
281                                            LOGGER.debug("sampleFeature " + sampleFeature);
282    
283                                  // The SLDStyleFactory has to be recreated, as it seams to cache                                  // The SLDStyleFactory has to be recreated, as it seams to cache
284                                  // some stuff.                                  // some stuff.
# Line 516  public class LegendIconFeatureRenderer e Line 290  public class LegendIconFeatureRenderer e
290                                                  size.height);                                                  size.height);
291    
292                                  if (style2d != null) {                                  if (style2d != null) {
293                                          new StyledShapePainter(null).paint(graphics, shape,                                          StyledShapePainter styledShapePainter = new StyledShapePainter(
294                                                          style2d, scaleDenominator);                                                          null);
295                                            styledShapePainter.paint(graphics, shape, style2d,
296                                                            Integer.MAX_VALUE);
297                                  }                                  }
298                          }                          }
299                  } catch (Exception e) {                  } catch (Exception e) {
300                          LOGGER                          LOGGER.error(
301                                          .error(                                          "Error during createImageForRule, returning empty Image", e);
                                                         "Error during createImageForRule, returning empty Image",  
                                                         e);  
302                  }                  }
303                  return buffImage;                  return buffImage;
304          }          }
# Line 533  public class LegendIconFeatureRenderer e Line 307  public class LegendIconFeatureRenderer e
307           * Define Java2D and other Hints           * Define Java2D and other Hints
308           *           *
309           * @param hints           * @param hints
310           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
          *         Kr&uuml;ger</a>  
311           */           */
312          public void setHints(Hints hints) {          public void setHints(Hints hints) {
313                  getHints().add(hints);                  getHints().add(hints);
# Line 559  public class LegendIconFeatureRenderer e Line 332  public class LegendIconFeatureRenderer e
332    
333          /**          /**
334           * Creates a little BufferedImage that presents the Style/Symbols used by           * Creates a little BufferedImage that presents the Style/Symbols used by
335           * the {@link MapLegend} to show a legend for the {@link FeatureType}           * the {@link MapLegend} to show a legend for the {@link SimpleFeatureType}
336           *           *
337           * @param rule           * @param rule
338           *            {@link Rule} that provides the text and the style to present           *            {@link Rule} that provides the text and the style to present
339           * @param featureType           * @param featureType
340           *            Schema that describes the kind of the sample {@link Feature}           *            Schema that describes the kind of the sample
341           *            that will be rendered with the {@link Style}           *            {@link SimpleFeature} that will be rendered with the
342             *            {@link Style}
343           *           *
344           * @throws IllegalAttributeException           * @throws IllegalAttributeException
345           */           */
346          public BufferedImage createImageForRule(final Rule rule,          public BufferedImage createImageForRule(final Rule rule,
347                          final FeatureType featureType, final Dimension size) {                          final SimpleFeatureType featureType, final Dimension size) {
348                  return createImageForRule(rule, featureType, size, null);                  return createImageForRule(rule, featureType, size, null);
349          }          }
350    

Legend:
Removed from v.244  
changed lines
  Added in v.1270

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26