图形如何在Java中绘制文本上方的线
我想在Java文本上方画一条线。我使用图形,以下是我的代码:
String s = a.getSequent().toString();
FontMetrics fm = getFontMetrics(getFont());
int textHeight = fm.getHeight();
int textWidth= fm.stringWidth(s);
//Text
g.drawString( s,
(int) ((jPanelWidth- textWidth) / 2),
(int) ((jPanelHeight- textHeight ) / 2));
//Draw line
int x1 = (jPanelWidth- textWidth) / 2;
int x2 = x1 + textWidth; //Problem
int y1 = (jPanelHeight- textHeight *4) / 2;
int y2 = y1;
g.drawLine(x1, y1, x2, y2);
以下是我所拥有的:
我不明白为什么这行的长度和我的文本不一样。问题在于x2的值,但为什么?你能帮我吗
# 1 楼答案
正如@luk2302所说,解决方案如下:
我有:
FontMetrics fm = getFontMetrics(getFont());
现在我有:
FontMetrics fm = getFontMetrics(g.getFont());
我没有使用正确的字体
# 2 楼答案
其中一个比较模糊的概念是理解文本实际上是如何呈现的
文本不是从x/y位置向下渲染,而是从基线向上渲染
这意味着x/y位置实际上代表基线。。。只要花点时间再读一遍,如果没有帮助,就读一读Measuring Text
基本的概念是,你需要取x/y位置,它代表基线,然后减去上升