/******************************************************************************* * 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.trend.impl; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import org.simantics.g2d.utils.GridUtil; import org.simantics.scenegraph.ExportableWidget.OutputWidget; /** * TextNode, the text is centered and scaled to fit inside the bounds. * * @author toni.kalajainen */ @OutputWidget("text") public class TextNode extends TrendGraphicalNode { private static final long serialVersionUID = 8508750881358776559L; String text = null; Font font = null; Color color = Color.BLACK; transient double sx, sy, tw, th, tx, ty; @SyncField("font") public void setFont(Font font) { this.font = font; } @SyncField("text") public void setText(String text) { this.text = text; } @SyncField("color") public void setColor(Color color) { this.color = color; } public void layout() { GlyphVector glyphVector = font.createGlyphVector(GridUtil.frc, text); Rectangle2D tr = glyphVector.getVisualBounds().getBounds2D(); tw = tr.getWidth(); th = tr.getHeight(); sx = getWidth() / tw; sy = getHeight() / th; tx = -tr.getX(); ty = -tr.getY(); // Fix horiz scale param sx if (sx<1.0) { // Text is too wide // Scale-down to fit rectangle width tw *= sx; th *= sx; sy *= sx; tx *= sx; ty *= sx; } else { // Text is ok horizontally. No need to scale. sx = 1.0; } // Fix vert scale param sy if (sy<1.0) { // Text is too tall // Scale-down to fit rectangle height tw *= sy; th *= sy; sx *= sy; tx *= sy; ty *= sy; } else { // Text is ok vertically. No need to scale. sy = 1.0; } tx += (bounds.getWidth() - tw) / 2; ty += (bounds.getHeight() - th) / 2; } @Override protected void doRender(Graphics2D g) { if (text == null || bounds == null || font == null || color == null) return; g.setFont(font); g.setColor(color); AffineTransform at = g.getTransform(); g.translate( bounds.getX(), bounds.getY() ); g.translate(tx, ty); g.scale(sx, sy); g.drawString(text, 0, 0); g.setTransform( at ); } }