
// StringMetrics.java
// https://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-string-in-java
// Modified by Andrew Davison, ad@coe.psu.ac.th, June 2023

/* Calculate the pixel dimensions of a string drawn in a 
   Graphics2D context using a specified font.
   Used by Banner.java

   Usage:
    > compile StringMetrics.java
*/


import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.awt.image.*;


public class StringMetrics 
{
  private Font font;
  private FontRenderContext context;


  public StringMetrics(Font f) 
  {
    font = f;
    BufferedImage im =
        new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
                        // use a dummy size 
    Graphics2D g2d = im.createGraphics();
    g2d.setFont(font);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    context = g2d.getFontRenderContext();
  }  // end of StringMetrics()


  public Rectangle getBounds(String s) 
  {   
    Rectangle2D bounds = font.getStringBounds(s, context);
    return new Rectangle( 0, 0, (int)bounds.getWidth(), 
                                (int)bounds.getHeight());
  }


  public int getWidth(String s) 
  {
    Rectangle bounds = getBounds(s);
    return (int)bounds.getWidth();
  }


  public int getHeight(String s) 
  {
    Rectangle bounds = getBounds(s);
    return (int)bounds.getHeight();
  }

}  // end of StringMetrics class