SwingChartUtil.java

  1. package de.slothsoft.charts.swing;

  2. import java.awt.Graphics2D;
  3. import java.awt.RenderingHints;
  4. import java.awt.image.BufferedImage;

  5. import de.slothsoft.charts.Area;
  6. import de.slothsoft.charts.Chart;
  7. import de.slothsoft.charts.PaintInstructions;

  8. /**
  9.  * Some util classes to generate stuff surrounding the {@link Chart} in Swing.
  10.  *
  11.  * @author Stef Schulz
  12.  * @since 0.2.0
  13.  */

  14. public final class SwingChartUtil {

  15.     /**
  16.      * Creates an {@link BufferedImage} from a chart.
  17.      *
  18.      * @param chart the chart to create an image for
  19.      * @param imageWidth the image's width
  20.      * @param imageHeight the image's height
  21.      * @return an image
  22.      */

  23.     public static BufferedImage createImage(Chart chart, int imageWidth, int imageHeight) {
  24.         final BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
  25.         final Graphics2D graphics2D = image.createGraphics();
  26.         graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  27.         try {
  28.             chart.paintOn(new Graphics2DGraphicContext(graphics2D),
  29.                     new PaintInstructions(new Area(imageWidth, imageHeight)));
  30.             return image;
  31.         } finally {
  32.             graphics2D.dispose();
  33.         }
  34.     }

  35.     private SwingChartUtil() {
  36.         // hide util class
  37.     }
  38. }