因爲您使用Typeface.MONOSPACE
,所以不必爲每個字符和每個文本大小計算文本邊界。
假設你有變量paint
,它的文本大小設置爲12開始。您想用文字填寫區域width
,height
。現在
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);
並繪製文本。
我沒有測試代碼,但它應該工作。如果您希望在必要時還能夠將文本大小減小到初始文本大小以下,則需要進行一些修改。
我不確定但是,Paint.getTextBounds()可能不考慮Typeface.MONOSPACE。難道你不能只計算允許空間字符的邊界,並使用該值來計算可以將多少個字符放入該區域,而不是重複調用Paint.getTextBounds()? – Onur
是的,當然。但我應該迭代文本大小來計算每個文本大小的總線寬度,並且它也需要太多時間 – 4ntoine