How to get height of text with fixed width and get text length which fits in a frame?

后端 未结 1 1649
孤城傲影
孤城傲影 2020-12-29 16:43

well, I\'ve managed to fit all my questions in the title. I need to break a long text in to columns/frames and layout them in to view. I\'ve been digging for solutions for a

相关标签:
1条回答
  • 2020-12-29 16:58

    I don't know the exact answer to your question, but generally you can calculate the width and height of a text based on the font type and size using methods available in the graphical library.

    I've done it in C# and Java. in C# it's called "MeasureString", and in Java, "FontMetrics".

    EDIT:

    See if this code is useful ( I haven't compiled it because I don't have android SDK here):

        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);
        }
    

    Similar methods are available for Android:

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

    Measure the text, stopping early if the measured width exceeds maxWidth.

    measureText(String text)
    

    Return the width of the text.

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

    0 讨论(0)
提交回复
热议问题