Java - 没有图形的精确字体高度

时间:2015-03-22 01:11:13

标签: java fonts

我有一个名为GUIText的对象,它有字符串文本,字体,字体样式,颜色和装饰(下划线,上划线,删除线)。我可以使用此方法获取GUIText的宽度,根据其文本和字体:

public int getWidth() {
    return Display.getCanvas().getFontMetrics(this.font.toJavaFont()).stringWidth(
            this.text);
}

(Display.getCanvas()返回一个JComponent) 我知道getFontMetrics()。getHeight(),但这会返回一个太大的数字。实际上,font.getSize()比getFontMetrics()。getHeight()更接近实际高度,但并不精确。我需要知道这一点,所以我可以在GUIText上画一条线来进行上线装饰。

1 个答案:

答案 0 :(得分:2)

也许TextLayout课程正是您要找的。它会给你准确的尺寸:

import javax.swing.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;

public class DrawTest extends JPanel
{
    String text;

    public DrawTest(String text)
    {
        this.text = text;
        setFont( new Font("Arial", Font.PLAIN, 24) );
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setFont( getFont() );
        g2d.setPaint(Color.RED);

        //  Draw text using FontMetrics

        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D rect = fm.getStringBounds(text, g2d);
        rect.setRect(rect.getX() + 100, rect.getY() + 50, rect.getWidth(), rect.getHeight());
        g2d.draw(rect);

        //  Draw text using TextLayout

        g2d.setPaint(Color.BLACK);

        Point2D loc = new Point2D.Float(100, 50);
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout layout = new TextLayout(text, getFont(), frc);
        layout.draw(g2d, (float)loc.getX(), (float)loc.getY());

        Rectangle2D bounds = layout.getBounds();
        bounds.setRect(bounds.getX()+loc.getX(), bounds.getY()+loc.getY(), bounds.getWidth(), bounds.getHeight());
        g2d.draw(bounds);
    }

    private static void createAndShowUI()
    {
        DrawTest text = new DrawTest("This is some ugly test");

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( text );
        frame.setSize(400, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}