gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:23:13 29 4
gpt4 key购买 nike

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

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

最佳答案

FontMetrics 是要使用的类:

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 方法的引用点,因此上升是您必须调整坐标的距离。如果您使用它使用 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 );

关于java - 字体 - 如何定位字符串的左上角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29726351/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com