Graphics2D 在绘制前获取 String 的维度

Graphics2D get String's dimension before drawing

在我的程序中,我正在绘制这样的字符串:

graphics2D.drawString(string, x, y);

但是,为了确定 x 和 y,我想知道该字符串的尺寸(高度和宽度)。我该怎么做?

您需要为此使用 FontMetrics class。您可以从 Graphics 对象中获取要使用的 FontMetrics,然后使用 stringWidthgetHeight 方法获取大小。

FontMetrics fm   = graphics2D.getFontMetrics();
int stringWidth  = fm.stringWidth(string);
int stringHeight = fm.getHeight();