How to get the height of the text with a fixed width and get the length of the text that matches the frame?

Well, I managed to ask all my questions in the title. I need to split long text into columns / frames and place them for viewing. I have long been versed in solutions, but I can not find examples or clear documentation on how to perform any of my tasks. I saw some mention of StaticLayout, but I don’t know how to use it correctly. Regarding the height of the text, I tried the TextPaint method getTextBounds, but it has no width limit and it looks like it measures only one row (well, maybe I did something wrong).

Maybe someone has an example of using StaticLayout or its subclass?

Everything looks so simple “on paper”: create a “frame”, check how many characters fit in it, fill out the frame and place it, repeat to the end of the text, and yet I can’t find anything about how to do this :)

+6
android android-layout paint
source share
1 answer

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

I have done this in C # and Java. in C # it is called "MeasureString", and in Java it is called "FontMetrics".

EDIT:

See if this code is useful (I didn’t compile it because I don’t have an 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); } 

Similar methods are available for Android:

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

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

 measureText(String text) 

Returns the width of the text.

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

+6
source share

All Articles