Java Font Text Bounds getStringBounds(Graphics2D g2, String s)

Here you can find the source of getStringBounds(Graphics2D g2, String s)

Description

Returns the @Rectangle2D surrounding a piece of text

License

Open Source License

Declaration

public static Dimension getStringBounds(Graphics2D g2, String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.Dimension;

import java.awt.Graphics2D;

import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

public class Main {
    /**/*  www.  j a  v a2s. c  om*/
     * Returns the @Rectangle2D surrounding a piece of text
     */
    public static Dimension getStringBounds(Graphics2D g2, String s) {
        if (isStringEmpty(s))
            return new Dimension();
        TextLayout layout = new TextLayout(s, g2.getFont(), g2.getFontRenderContext());
        Rectangle2D bounds = layout.getBounds();
        return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight());
    }

    public static boolean isStringEmpty(String s) {
        return (s == null || s.length() == 0);
    }
}

Related

  1. getStringBounds(Graphics2D g, Font font, String s)
  2. getStringBounds(Graphics2D g2, String str, float x, float y)
  3. getStringBounds(Graphics2D g2d, String text, int x, int y)
  4. getStringBounds(String s, Graphics g)
  5. getStringBounds(String str, java.awt.Font font)