A utility method that calculates the anchor offsets for a string. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

A utility method that calculates the anchor offsets for a string.

Demo Code

/* ===========================================================
 * Orson Charts : a 3D chart library for the Java(tm) platform
 * ===========================================================
 * //from  w  ww .j a  v  a2  s .  co m
 * (C)opyright 2013-2016, by Object Refinery Limited.  All rights reserved.
 * 
 * http://www.object-refinery.com/orsoncharts/index.html
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
 * Other names may be trademarks of their respective owners.]
 * 
 * If you do not wish to be bound by the terms of the GPL, an alternative
 * commercial license can be purchased.  For details, please see visit the
 * Orson Charts home page:
 * 
 * http://www.object-refinery.com/orsoncharts/index.html
 * 
 */
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;

public class Main{
    /**
     * A utility method that calculates the anchor offsets for a string.
     * Normally, the {@code (x, y)} coordinate for drawing text is a point on 
     * the baseline at the left of the text string.  If you add these offsets 
     * to {@code (x, y)} and draw the string, then the anchor point should 
     * coincide with the {@code (x, y)} point.
     *
     * @param g2  the graphics device (not {@code null}).
     * @param text  the text.
     * @param anchor  the anchor point ({@code null} not permitted).
     *
     * @return  The offsets.
     */
    private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
            String text, TextAnchor anchor) {

        float[] result = new float[2];
        FontRenderContext frc = g2.getFontRenderContext();
        Font f = g2.getFont();
        FontMetrics fm = g2.getFontMetrics(f);
        Rectangle2D bounds = getTextBounds(text, fm);
        LineMetrics metrics = f.getLineMetrics(text, frc);
        float ascent = metrics.getAscent();
        float halfAscent = ascent / 2.0f;
        float descent = metrics.getDescent();
        float leading = metrics.getLeading();
        float xAdj = 0.0f;
        float yAdj = 0.0f;

        if (anchor.isHorizontalCenter()) {
            xAdj = (float) -bounds.getWidth() / 2.0f;
        } else if (anchor.isRight()) {
            xAdj = (float) -bounds.getWidth();
        }

        if (anchor.isTop()) {
            yAdj = -descent - leading + (float) bounds.getHeight();
        } else if (anchor.isHalfAscent()) {
            yAdj = halfAscent;
        } else if (anchor.isHalfHeight()) {
            yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
        } else if (anchor.isBaseline()) {
            yAdj = 0.0f;
        } else if (anchor.isBottom()) {
            yAdj = -metrics.getDescent() - metrics.getLeading();
        }
        result[0] = xAdj;
        result[1] = yAdj;
        return result;
    }
    /**
     * A utility method that calculates the anchor offsets for a string.
     * Normally, the {@code (x, y)} coordinate for drawing text is a point on 
     * the baseline at the left of the text string.  If you add these offsets 
     * to {@code (x, y)} and draw the string, then the anchor point should 
     * coincide with the {@code (x, y)} point.
     *
     * @param g2  the graphics device (not {@code null}).
     * @param text  the text.
     * @param anchor  the anchor point ({@code null} not permitted).
     * @param textBounds  the text bounds (if not {@code null}, this
     *                    object will be updated by this method to match the
     *                    string bounds).
     *
     * @return  The offsets.
     */
    private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
            String text, TextAnchor anchor, Rectangle2D textBounds) {

        float[] result = new float[3];
        FontRenderContext frc = g2.getFontRenderContext();
        Font f = g2.getFont();
        FontMetrics fm = g2.getFontMetrics(f);
        Rectangle2D bounds = getTextBounds(text, fm);
        LineMetrics metrics = f.getLineMetrics(text, frc);
        float ascent = metrics.getAscent();
        result[2] = -ascent;
        float halfAscent = ascent / 2.0f;
        float descent = metrics.getDescent();
        float leading = metrics.getLeading();
        float xAdj = 0.0f;
        float yAdj = 0.0f;

        if (anchor.isHorizontalCenter()) {
            xAdj = (float) -bounds.getWidth() / 2.0f;
        } else if (anchor.isRight()) {
            xAdj = (float) -bounds.getWidth();
        }

        if (anchor.isTop()) {
            yAdj = -descent - leading + (float) bounds.getHeight();
        } else if (anchor.isHalfAscent()) {
            yAdj = halfAscent;
        } else if (anchor.isHorizontalCenter()) {
            yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
        } else if (anchor.isBaseline()) {
            yAdj = 0.0f;
        } else if (anchor.isBottom()) {
            yAdj = -metrics.getDescent() - metrics.getLeading();
        }
        if (textBounds != null) {
            textBounds.setRect(bounds);
        }
        result[0] = xAdj;
        result[1] = yAdj;
        return result;
    }
    /**
     * Calculates the x and y offsets required to align the text with the
     * specified {@code anchor}.
     * 
     * @param g2  the graphics target ({@code null} not permitted).
     * @param text  the text ({@code null} not permitted).
     * @param anchor  the anchor ({@code null} not permitted).
     * @param textBounds  if not {@code null}, this rectangle will be
     *     updated with the bounds of the text (for the caller to use).
     * 
     * @return An array of two floats dx and dy.
     */
    private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
            AttributedString text, TextAnchor anchor, Rectangle2D textBounds) {

        TextLayout layout = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
        Rectangle2D bounds = layout.getBounds();

        float[] result = new float[3];
        float ascent = layout.getAscent();
        result[2] = -ascent;
        float halfAscent = ascent / 2.0f;
        float descent = layout.getDescent();
        float leading = layout.getLeading();
        float xAdj = 0.0f;
        float yAdj = 0.0f;

        if (anchor.isHorizontalCenter()) {
            xAdj = (float) -bounds.getWidth() / 2.0f;
        } else if (anchor.isRight()) {
            xAdj = (float) -bounds.getWidth();
        }

        if (anchor.isTop()) {
            yAdj = -descent - leading + (float) bounds.getHeight();
        } else if (anchor.isHalfAscent()) {
            yAdj = halfAscent;
        } else if (anchor.isHalfHeight()) {
            yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
        } else if (anchor.isBaseline()) {
            yAdj = 0.0f;
        } else if (anchor.isBottom()) {
            yAdj = -descent - leading;
        }
        if (textBounds != null) {
            textBounds.setRect(bounds);
        }
        result[0] = xAdj;
        result[1] = yAdj;
        return result;
    }
    /**
     * Returns the bounds for the specified text.  The supplied text is
     * assumed to be on a single line (no carriage return or newline 
     * characters).
     *
     * @param text  the text ({@code null} not permitted).
     * @param fm  the font metrics ({@code null} not permitted).
     *
     * @return The text bounds.
     */
    public static Rectangle2D getTextBounds(String text, FontMetrics fm) {
        return getTextBounds(text, 0.0, 0.0, fm);
    }
    /**
     * Returns the bounds for the specified text when it is drawn with the 
     * left-baseline aligned to the point {@code (x, y)}.
     * 
     * @param text  the text ({@code null} not permitted).
     * @param x  the x-coordinate.
     * @param y  the y-coordinate.
     * @param fm  the font metrics ({@code null} not permitted).
     * 
     * @return The bounding rectangle (never {@code null}). 
     */
    public static Rectangle2D getTextBounds(String text, double x,
            double y, FontMetrics fm) {
        ArgChecks.nullNotPermitted(text, "text");
        ArgChecks.nullNotPermitted(fm, "fm");
        double width = fm.stringWidth(text);
        double height = fm.getHeight();
        return new Rectangle2D.Double(x, y - fm.getAscent(), width, height);
    }
}

Related Tutorials