2014-05-11 37 views
2

我需要檢測適合文本(寬度,高度)的最大文本大小。什麼是獲取文字大小值的最快捷方式?在android中獲取文本寬度的最有效方法是什麼?

我試過迭代循環中的文本大小,並得到Paint.getTextBounds(),但它需要很多時間,整個調用需要幾秒鐘。油漆字體是Typeface.MONOSPACE,這應該有助於節省時間,因爲字符寬度相等。文本大小和字符寬度之間是否存在任何依賴關係,以避免調用Paint.getTextBounds()?這個任務與爲TextView獲取文本大小的寬度和高度非常相似,所以任何人都知道如何快速做到這一點?

+0

我不確定但是,Paint.getTextBounds()可能不考慮Typeface.MONOSPACE。難道你不能只計算允許空間字符的邊界,並使用該值來計算可以將多少個字符放入該區域,而不是重複調用Paint.getTextBounds()? – Onur

+0

是的,當然。但我應該迭代文本大小來計算每個文本大小的總線寬度,並且它也需要太多時間 – 4ntoine

回答

0

因爲您使用Typeface.MONOSPACE,所以不必爲每個字符和每個文本大小計算文本邊界。

假設你有變量paint,它的文本大小設置爲12開始。您想用文字填寫區域widthheight。現在

Rect initialBounds = new Rect(); 
paint.getTextBounds(" ", 0, 1, initialBounds); 
float initialTextSize = 12, increase = 2, currentSize = 12; 
int charCount = text.length();//the char count we want to print 
int maxCharCount = 0;//max count of chars we can print at currentSize. 
do{ 
    currentSize += increase; 
    float charWidth = initialBounds.right * currentSize/initialTextSize; 
    float charHeight = initialBounds.bottom * currentSize/initialTextSize; 
    int charPerLine = width/charWidth; 
    int lineCount = height/charHeight; 
    maxCharCount = charPerLine * lineCount; 
} 
while(maxCharCount > charCount); 
currentSize -= increase;//this is the size we are looking for. 

之後,你可以撥打paint.setTextSize(currentSize);並繪製文本。

我沒有測試代碼,但它應該工作。如果您希望在必要時還能夠將文本大小減小到初始文本大小以下,則需要進行一些修改。

+0

您確定它是文本大小和寬度之間的線性依賴關係,因此您可以使用'initialBounds.right * currentSize/initialTextSize'?如果這是真的,則可以將最大文本大小計算爲'final_text_size = max_width/cur_width * cur_text_size'而不進行迭代 – 4ntoine

相關問題