01: package com.vividsolutions.jump.workbench.ui;
02:
03: import java.awt.Color;
04: import java.awt.Graphics2D;
05: import java.awt.image.BufferedImage;
06: import java.util.ArrayList;
07: import java.util.Collection;
08: import java.util.Collections;
09: import java.util.Iterator;
10:
11: import com.vividsolutions.jts.geom.Envelope;
12: import com.vividsolutions.jts.util.Assert;
13: import com.vividsolutions.jump.workbench.model.Layer;
14: import com.vividsolutions.jump.workbench.model.Layerable;
15: import com.vividsolutions.jump.workbench.ui.renderer.LayerRenderer;
16:
17: /**
18: * Renders layers as an Image, which can then be saved to a file or printed.
19: */
20: public class LayerPrinter {
21:
22: /**
23: * @param layers earlier layers will be rendered above later layers
24: */
25: public BufferedImage print(Collection layers, Envelope envelope,
26: int extentInPixels) throws Exception {
27: Assert.isTrue(!layers.isEmpty());
28:
29: final Throwable[] throwable = new Throwable[] { null };
30: LayerViewPanel panel = new LayerViewPanel(((Layer) layers
31: .iterator().next()).getLayerManager(),
32: new LayerViewPanelContext() {
33: public void setStatusMessage(String message) {
34: }
35:
36: public void warnUser(String warning) {
37: }
38:
39: public void handleThrowable(Throwable t) {
40: throwable[0] = t;
41: }
42: });
43: panel.setSize(extentInPixels, extentInPixels);
44: panel.getViewport().zoom(envelope);
45:
46: BufferedImage bufferedImage = new BufferedImage(panel
47: .getWidth(), panel.getHeight(),
48: BufferedImage.TYPE_INT_ARGB);
49: Graphics2D graphics = bufferedImage.createGraphics();
50: paintBackground(graphics, extentInPixels);
51:
52: ArrayList layersReversed = new ArrayList(layers);
53: Collections.reverse(layersReversed);
54:
55: for (Iterator i = layersReversed.iterator(); i.hasNext();) {
56: Layer layer = (Layer) i.next();
57:
58: LayerRenderer renderer = new LayerRenderer(layer, panel);
59:
60: //Wait for rendering to complete rather than running it in a separate thread. [Jon Aquino]
61: Runnable runnable = renderer.createRunnable();
62: if (runnable != null) {
63: runnable.run();
64: }
65:
66: //I hope no ImageObserver is needed. Set to null. [Jon Aquino]
67: renderer.copyTo(graphics);
68: }
69:
70: if (throwable[0] != null) {
71: throw throwable[0] instanceof Exception ? (Exception) throwable[0]
72: : new Exception(throwable[0].getMessage());
73: }
74:
75: return bufferedImage;
76: }
77:
78: private void paintBackground(Graphics2D graphics, int extent) {
79: graphics.setColor(Color.white);
80: graphics.fillRect(0, 0, extent, extent);
81: }
82:
83: }
|