/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.g2d.chassis; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.simantics.g2d.canvas.ICanvasContext; import org.simantics.g2d.canvas.IContentContext; import org.simantics.g2d.canvas.IContentContext.IContentListener; import org.simantics.scenegraph.g2d.G2DRenderingHints; /** * Renders canvas to an image. * * @author Toni Kalajainen */ public class ImageChassis extends AbstractChassis { public static final Color WIPE_COLOR = new Color(.0f, 0.f, 0.f, .0f); private Color backgroundColor; Image image; boolean dirty = false; public ImageChassis(Image image) { this.image = image; } public void setBackgroundColor(Color color) { backgroundColor = color; } public Point2D getSize() { return new Point2D.Double(image.getWidth(null), image.getHeight(null)); } public Rectangle2D getBounds() { return new Rectangle2D.Double(0,0,image.getWidth(null), image.getHeight(null)); } @Override public void setCanvasContext(ICanvasContext canvasContext) { super.setCanvasContext(canvasContext); canvasContext.getContentContext().addPaintableContextListener(new IContentListener() { @Override public void onDirty(IContentContext sender) { if (dirty) return; dirty = true; draw(); }}); draw(); } public void draw() { if (canvasContext.isLocked()) throw new IllegalStateException("cannot draw image, canvas context is locked: " + canvasContext); dirty = false; Graphics2D g2d = (Graphics2D) image.getGraphics(); try { g2d.setRenderingHint(G2DRenderingHints.KEY_CONTROL_BOUNDS, getBounds()); if(backgroundColor != null) { Rectangle2D bounds = getBounds(); g2d.setBackground(backgroundColor); g2d.clearRect(0, 0, (int)bounds.getWidth(), (int)bounds.getHeight() ); } canvasContext.getSceneGraph().render(g2d); } finally { g2d.dispose(); } } }