字体 - 如何定位字符串的左上角?

Fonts - How to position top-left corner of a string?

假设我想使用 java.awt.Graphics.drawString(String str, int x, int y) 方法在某些特定坐标处绘制字符串,例如 (300, 300)。然而,drawString() 方法将始终将字符串 的 左下角定位在这些坐标处,而不是我想要的左上角。

在指定坐标处绘制字符串左上角的简单方法是什么?我知道 java.awt.FontMetrics 实用程序 class 但我很确定它是否有用。

试试这个:

FontMetrics metric = g.getFontMetrics(g.getFont());
g.drawString(str, x, y + metric.getAscent() - metric.getDescent() - metric.getLeading());

FontMetrics 是 class 使用的:

public static int getStringAscent(Graphics page, Font f, String s) {
    // Find the size of string s in the font of the Graphics context "page"
    FontMetrics fm   = page.getFontMetrics(f);
    return fm.getAscent();
}

上升是给定字符串从基线上升起的最大高度字形。基线的起点是 drawString 方法的参考点,因此 ascent 是您必须调整坐标的距离。如果您使用它使用 Graphics2D g:

绘制字符串
g.drawString(msg, x, y);

你可以将它向下移动字体 f 的上升高度:

Font small = new Font("Helvetica", Font.BOLD, 24);
FontMetrics metrics = getFontMetrics(small);
int d = metrics.getAscent();

g.drawString(msg, x, y + d );