如何在Java中绘制一个垂直居中的字符串?

Pau*_*der 20 java graphics

我知道这是一个简单的概念,但我正在努力使用字体指标.水平居中并不太难,但垂直方向看起来有点困难.

我尝试过各种组合使用FontMetrics getAscent,getLeading,getXXXX方法,但无论我尝试过什么,文本总是偏离几个像素.有没有办法测量文本的确切高度,使其完全居中.

Law*_*Dol 48

请注意,你需要精确地考虑您的垂直居中的意思.

字体在基线上呈现,沿文本底部运行.垂直空间分配如下:

---
 ^
 |  leading
 |
 -- 
 ^              Y     Y
 |               Y   Y
 |                Y Y
 |  ascent         Y     y     y 
 |                 Y      y   y
 |                 Y       y y
 -- baseline ______Y________y_________
 |                         y                
 v  descent              yy
 --
Run Code Online (Sandbox Code Playgroud)

前导只是字体在行之间的推荐空间.为了在两点之间垂直居中,你应该忽略前导(它的led,BTW,而不是le ;;在一般的排版中,它是/是在印版中的线之间插入的引线间距).

因此,为了使文本上升和下降器居中,你需要

baseline=(top+((bottom+1-top)/2) - ((ascent + descent)/2) + ascent;
Run Code Online (Sandbox Code Playgroud)

没有最终的"+上升",你就有了字体顶部的位置; 因此,添加上升从顶部到基线.

此外,请注意字体高度应包括前导,但有些字体不包括它,并且由于舍入差异,字体高度可能不完全相等(前导+上升+下降).


Ott*_*ger 11

我在这里找到了一个食谱.

关键的方法似乎是getStringBounds()getAscent()

// Find the size of string s in font f in the current Graphics context g.
FontMetrics fm   = g.getFontMetrics(f);
java.awt.geom.Rectangle2D rect = fm.getStringBounds(s, g);

int textHeight = (int)(rect.getHeight()); 
int textWidth  = (int)(rect.getWidth());
int panelHeight= this.getHeight();
int panelWidth = this.getWidth();

// Center text horizontally and vertically
int x = (panelWidth  - textWidth)  / 2;
int y = (panelHeight - textHeight) / 2  + fm.getAscent();

g.drawString(s, x, y);  // Draw the string.
Run Code Online (Sandbox Code Playgroud)

(注意:上面的代码由MIT许可证涵盖,如页面上所述.)

  • 是的......我对这个概念很熟悉......但这是错的.fm.getAscent()方法就是问题所在.它不报告字体的实际像素上升,并导致文本比顶部更接近底部. (2认同)