Java Font Text Bounds getTextBounds(Graphics graphics, String text)

Here you can find the source of getTextBounds(Graphics graphics, String text)

Description

Get the bounds for drawing the specified text in the specified graphics context.

License

Open Source License

Parameter

Parameter Description
graphics A graphics context.
text A text.

Return

The bounds as described above.

Declaration

public static Rectangle getTextBounds(Graphics graphics, String text) 

Method Source Code


//package com.java2s;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Main {
    /**//from www .  j  a v a 2s .  c  o  m
     * Get the bounds for drawing the specified text in the specified graphics context. The bounds
     * returned contain the correct width and height for the text. The x position is always set to 0
     * and the y position specifies the maximum text ascend. So drawing the text with the x and y
     * coordinate from the returned rectangle makes the text appear in the upper left corner of the
     * target context.
     *
     * @param graphics A graphics context.
     * @param text     A text.
     *
     * @return The bounds as described above.
     */
    public static Rectangle getTextBounds(Graphics graphics, String text) {
        FontMetrics metrics = graphics.getFontMetrics();
        Rectangle2D textBounds = metrics.getStringBounds(text, graphics);
        int textAscend = metrics.getMaxAscent();
        return new Rectangle(0, textAscend, (int) textBounds.getWidth(), textAscend + metrics.getMaxDescent());
    }
}

Related

  1. getTextBounds(AttributedString text, Graphics2D g2)
  2. getTextBounds(final Graphics2D graphics, final String text, final Font font)
  3. getTextBounds(final String text, final Graphics g, final Font font)
  4. getTextBounds(Graphics g, Font font, String text, int x, int y, int halign, int valign)
  5. getTextBounds(Graphics g, String text)
  6. getTextBounds(Graphics2D g, Font font, String text)
  7. getTextBounds(String text, Graphics2D g2, FontMetrics fm)
  8. getTextBox(Font font, FontRenderContext frc, boolean withLeading, String text)