2012-01-19 38 views
6

如何獲得給定字符串下行的高度?如何獲得給定字符串下行的高度?

enter image description here

例如,

  • abc應該返回0
  • abcl應該返回0
  • abcp應從descnder線返回到基線距離。
  • abclp應該返回從descnder行到基線的距離。

盡我所能出來至今

private int getDecender(String string, Paint paint) { 
    // Append "l", to ensure there is Ascender 
    string = string + "l"; 
    final String stringWithoutDecender = "l"; 

    final Rect bounds = new Rect(); 
    final Rect boundsForStringWithoutDecender = new Rect(); 
    paint.getTextBounds(string, 0, string.length(), bounds); 
    paint.getTextBounds(stringWithoutDecender, 0, stringWithoutDecender.length(), boundsForStringWithoutDecender); 
    return bounds.height() - boundsForStringWithoutDecender.height(); 
} 

然而,我的代碼的氣味是他們不夠好。有沒有更好更快的方法?

回答

-1

你應該看看Paint.FontMetrics。下降成員會給你「推薦距離低於基線的單獨間隔文本。」。

+0

問題如何找出,在給定的字符串中是否有任何非零下降的字符。 –

+0

對不起,我讀得太快了。你的代碼中可能有最好的解決方案。 – emidander

3

其實我正在尋找相同的功能。事實證明,有更簡單的方法,你甚至不需要單獨的功能。

如果您只是在給定字符串上調用getTextBounds(),則返回的邊界框將已經具有該信息。

例如:

paint.getTextBounds(exampleString1 , 0, exampleString1.length(), bounds); 

if (bounds.bottom > 0) Log.i("Test", "String HAS descender"); 
else Log.i("Test", "String DOES NOT HAVE descender"); 

只需說bounds.top告訴您字符串的上升(它具有負的值作爲Y軸0點是在所述串的基線)和bounds.bottom告訴您字符串的下降(對於具有下降的字符串,可以爲0或正值)。

相關問題