2013-01-11 121 views
5

我有一個名爲Hello的文本,現在我需要爲此說12或18應用fontsize,只要我們將字體應用於文本大小增加的文本。獲取包含字體大小的文本高度並設置該高度

所以現在我需要使用paint來獲取包括字體大小的文本高度。

我曾嘗試用油漆以下:

String finalVal ="Hello"; 

Paint paint = new Paint(); 
paint.setTextSize(18); 
paint.setTypeface(Typeface.SANS_SERIF); 
paint.setColor(Color.BLACK); 
paint.setStyle(Paint.Style.FILL); 

Rect result = new Rect(); 
// Measure the text rectangle to get the height 
paint.getTextBounds(finalVal, 0, finalVal.length(), result); 

但它不工作,請幫助

編輯

我想設置的WebView的動態基礎上,高度textheight我得到像"Hello"單線的文本高度,但如果有兩行文本"My name is abc and my dads name is xyz and my moms name is 123" now its not getting the proper text height".

+0

究竟什麼不起作用? –

+0

請看我編輯 – Goofy

+0

嗯......聽起來很奇怪。你爲什麼需要這樣做? –

回答

7

試試這個方法:

String finalVal ="Hello"; 

Paint paint = new Paint(); 
paint.setTextSize(18); 
paint.setTypeface(Typeface.SANS_SERIF); 
paint.setColor(Color.BLACK); 
paint.setStyle(Paint.Style.FILL); 

Rect result = new Rect(); 
paint.getTextBounds(finalVal, 0, finalVal.length(), result); 

Log.d("WIDTH  :", String.valueOf(result.width())); 
Log.d("HEIGHT  :", String.valueOf(result.height())); 

這裏是輸出:

WIDTH  : 40 
HEIGHT  : 14 

如果我設置,

String finalVal ="My name is abc and my dads name is xyz and my moms name is 123"; 

我的輸出是:

WIDTH  : 559 
HEIGHT  : 18 
+0

感謝你回答我以前做過這個,我也得到了相同的答案,但我們要根據設備的高度和寬度來設置它,因爲你可以看到你好詞和多行高度doesent有很大差異 – Goofy

2

你可以從中獲取文字高度FontMetrics。無論當前的文本字符串是什麼,對於特定的字體和字體大小都是不變的。

Paint.FontMetrics fm = mTextPaint.getFontMetrics(); 
float textHeight = fm.descent - fm.ascent; 
float lineHeight = fm.bottom - fm.top + fm.leading; 

查看我更完整的答案here。我在那個答案中比較了getTextBoundsFontMetrics

相關問題