Font base line : Font Metrics « 2D Graphics « Java Tutorial






import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class FontShow extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Font font = new Font("Dialog", Font.PLAIN, 96);
    g2.setFont(font);
    int width = getSize().width;
    int height = getSize().height;

    String message = "Java2s";

    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics metrics = font.getLineMetrics(message, frc);
    float messageWidth = (float) font.getStringBounds(message, frc).getWidth();

    // center text
    float ascent = metrics.getAscent();
    float descent = metrics.getDescent();
    float x = (width - messageWidth) / 2;
    float y = (height + metrics.getHeight()) / 2 - descent;

    int PAD = 25;
    g2.setPaint(getBackground());
    g2.fillRect(0, 0, width, height);

    g2.setPaint(getForeground());
    g2.drawString(message, x, y);

    g2.setPaint(Color.white); // Base lines
    drawLine(g2, x - PAD, y, x + messageWidth + PAD, y);
    drawLine(g2, x, y + PAD, x, y - ascent - PAD);
    g2.setPaint(Color.green); // Ascent line
    drawLine(g2, x - PAD, y - ascent, x + messageWidth + PAD, y - ascent);
    g2.setPaint(Color.red); // Descent line
    drawLine(g2, x - PAD, y + descent, x + messageWidth + PAD, y + descent);
  }

  private void drawLine(Graphics2D g2, double x0, double y0, double x1, double y1) {
    Shape line = new java.awt.geom.Line2D.Double(x0, y0, x1, y1);
    g2.draw(line);
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setSize(420, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new FontShow());
    frame.setVisible(true);
  }
}








16.24.Font Metrics
16.24.1.Font Metrics: the wealth of dimensional data about a font
16.24.2.Font base line
16.24.3.Getting Char with based on current font
16.24.4.calls stringWidth (String) to center several text messagescalls stringWidth (String) to center several text messages
16.24.5.Center text.Center text.
16.24.6.Draw text to the leftDraw text to the left
16.24.7.Draw text to the rightDraw text to the right
16.24.8.Draw text to the centerDraw text to the center
16.24.9.Text justifyText justify
16.24.10.Draw font metrics
16.24.11.Display a text in 3 dimensions
16.24.12.Obtain FontMetrics of different fonts