LineMetrics Example
A string has a baseline (the line you use when you write on ruled paper), an ascent (the greatest height above the baseline), and a descent (the furthest distance below the baseline). These details are provided by LineMetrics methods. This program draws a blue baseline, a red descent line, and a green ascent line for the particular font being used - not the string.
// LineMetrics Example
import java.awt.*;
import javax.swing.*;
import java.awt.font.*;
import java.awt.geom.*;
class LineMetricsExample extends JApplet {
@Override public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
Font font = new Font("Serif", Font.PLAIN, 36);
g2.setFont(font);
int w=300, h=300; // size of the graphics environment
String s = "happily";
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics lineMetrics = font.getLineMetrics(s, frc);
int stringWidth = (int)font.getStringBounds(s, frc).getWidth();
int ascent = (int)lineMetrics.getAscent();
int descent = (int)lineMetrics.getDescent();
int x = (w - stringWidth) / 2;
int y = (h + (int)lineMetrics.getHeight()) / 2 - descent; // baseline
g2.drawString(s, x, y);
int gap=5;
g2.setPaint(Color.blue);
g2.drawLine(x - gap, y, x + stringWidth + gap, y);
g2.setPaint(Color.green);
g2.drawLine(x - gap, y - ascent, x + stringWidth + gap, y - ascent);
g2.setPaint(Color.red);
g2.drawLine(x - gap, y + descent, x + stringWidth + gap, y + descent);
}
}
