如何获得具有固定宽度的文本高度并获得适合框架的文本长度?

时间:2010-12-01 08:10:07

标签: android android-layout paint

好吧,我已经设法将所有问题都放在标题中。我需要将一个长文本分成列/帧并将它们布局到视图中。我一直在寻找解决方案几天,但我找不到任何关于如何完成任务的示例或明确的文档。我看过一些提到的StaticLayout,但我不知道如何正确使用它。至于文本高度,我尝试过TextPaint的getTextBounds方法,但它没有宽度限制,看起来它只测量单行(好吧,也许我做错了)。

也许某人有一个StaticLayout的例子或它的子类用法?

一切看起来如此简单“在纸上”:创建“框架”,检查多少字符适合它,填充框架并定位它,重复直到文本结束但我找不到任何关于如何执行此操作: )

1 个答案:

答案 0 :(得分: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