Draw font base line in Java

Description

The following code shows how to draw font base line.

Example


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;
/*from w  w w  .  j a v a2 s.com*/
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas 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.com";

    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 class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Draw font base line in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform