2010-12-01 61 views
6

好吧,我已經設法將所有的問題都放在標題中。我需要將長文本分解爲列/幀並將它們佈置在視圖中。我一直在挖掘解決方案几天,但我找不到任何示例或明確的文檔說明如何完成我的任務。我見過一些提到的StaticLayout,但我不知道如何正確使用它。至於文字高度,我嘗試過TextPaint的getTextBounds方法,但它沒有寬度限制,它看起來像只測量一行(好吧,也許我做錯了什麼)。如何獲得固定寬度的文本高度並獲得適合框架的文本長度?

也許有人有一個StaticLayout的例子或它的子類的用法?

一切看起來如此簡單「在紙上」:創建「框架」,檢查多少字符適合它,填充框架和位置,重複,直到文本結束,但我找不到任何關於如何做到這一點:)

+0

難道u檢驗的代碼? – 2010-12-12 09:10:19

回答

6

我不知道您的問題的確切答案,但通常您可以使用圖形庫中可用的方法計算基於字體類型和大小的文本的寬度和高度。

我已經在C#和Java中完成了它。在C#中稱爲「MeasureString」,在Java中稱爲「FontMetrics」。

編輯:

看看這個代碼是有用的(因爲我沒有在這裏Android SDK中我還沒有編譯它):

String myText="";  
    String tempStr=""; 

    int startIndex=0; 
    int endIndex=0; 

    //calculate end index that fits 
    endIndex=myPaint.breakText(myTest, true, frameWidth, null)-1; 

    //substring that fits into the frame 
    tempStr=myText.substring(startIndex,endIndex); 

    while(endIndex < myText.length()-1) 
    {   

     //draw or add tempStr to the Frame 
     //at this point 

     //set new start index 
     startIndex=endIndex+1; 

     //substring the remaining of text 
     tempStr=myText.substring(startIndex,myText.length()-1); 

     //calculate end of index that fits 
     endIndex=myPaint.breakText(tempStr, true, frameWidth, null)-1; 

     //substring that fits into the frame 
     tempStr=myText.substring(startIndex,endIndex); 
    } 

類似的方法也可用於Android:

breakText(String text, boolean measureForwards, float maxWidth, float[] measuredWidth) 

測量文本,如果測量的寬度超過maxWidth,則提前停止。

measureText(String text) 

返回文本的寬度。

http://developer.android.com/reference/android/graphics/Paint.html

+0

在android,@sniurkst中沒有工作,如果你有完美的答案,那麼請張貼它。 – Jayesh 2017-02-08 13:11:10

相關問題