[英]How do you draw a string centered vertically in Java?
我知道這是一個簡單的概念,但我正在努力使用字體指標。 水平居中並不太難,但垂直方向似乎有點困難。
我嘗試過各種組合使用FontMetrics getAscent,getLeading,getXXXX方法,但無論我嘗試過什么,文本總是偏離幾個像素。 有沒有辦法測量文本的確切高度,使其完全居中。
請注意,你就需要精確地考慮您的垂直居中的意思。
字體在基線上呈現,沿文本底部運行。 垂直空間分配如下:
---
^
| leading
|
--
^ Y Y
| Y Y
| Y Y
| ascent Y y y
| Y y y
| Y y y
-- baseline ______Y________y_________
| y
v descent yy
--
前導只是字體在行之間的推薦空間。 為了在兩點之間垂直居中,你應該忽略前導(它的led,BTW,而不是leeding;在一般的排版中,它是/是在印版中的線之間插入的引線間距)。
因此,為了使文本上升和下降器居中,你需要
baseline=(top+((bottom+1-top)/2) - ((ascent + descent)/2) + ascent;
沒有最終的“+上升”,你就有了字體頂部的位置; 因此,添加上升從頂部到基線。
此外,請注意字體高度應包括前導,但有些字體不包括它,並且由於舍入差異,字體高度可能不完全相等(前導+上升+下降)。
我在這里找到了一個食譜。
關鍵方法似乎是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.
(注意:上面的代碼由MIT許可證涵蓋,如頁面上所述。)
不確定這有用,但drawString(s, x, y)
在y處設置文本的基線 。
我正在做一些垂直居中,並且在我注意到文檔中提到的行為之前無法讓文本看起來正確。 我假設字體的底部是y。
對我來說,修復是從y坐標中減去fm.getDescent()
。
另一個選項是TextLayout類的getBounds方法。
Font f;
// code to create f
String TITLE = "Text to center in a panel.";
FontRenderContext context = g2.getFontRenderContext();
TextLayout txt = new TextLayout(TITLE, f, context);
Rectangle2D bounds = txt.getBounds();
int xString = (int) ((getWidth() - bounds.getWidth()) / 2.0 );
int yString = (int) ((getHeight() + bounds.getHeight()) / 2.0);
// g2 is the graphics object
g2.setFont(f);
g2.drawString(TITLE, xString, yString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.