Finding cutoff character of MeasureStringWidth

joseluis

Active Member
Licensed User
Longtime User
Hi, I want to know your ideas about the most best way of doing the following.

I have label for writing some text on it, and I have a long string that I can check if it fits with MeasureStringWidth canvas method. e.g.:
B4X:
Label.Width == 50
cnv.MeasureStringWidth(Text, Typeface, TextSize) == 258

When it doesn't fit, like in the previous example, I want to find out the character's index at the cutoff.

So, I thought of several ideas, but I want to know if there's a better way to do it:

1) The most inefficient way I can think of is to go backward 1 character at a time, until MeasureStringWidth < Label.Width

2) Do it by halves. Measure half of the string, compare widths, and repeat the process reducing the margin until finding the index.

3) ??


Any more ideas?
 

stevel05

Expert
Licensed User
Longtime User
If you use a fixed width font you can calculate it directly. If not your binary chop should be good.
 
Upvote 0

joseluis

Active Member
Licensed User
Longtime User
No, it must work with non-fixed fonts too.

I'll implement the second system I posted, but you gave me an idea for improving the number of guesses, maybe.

Just measure the size of an average letter (char a?), and then instead of starting the search in the middle of the string, start at the index of the result of dividing Label.Width / char's width.

I think that could very much improve performance with very long strings, since I must repeat that process for every line, inserting CRLF on the cutoffs until I fill all the text in the label...
 
Upvote 0

joseluis

Active Member
Licensed User
Longtime User
Because I don't know the height of the label on advance, only the width.
The height must be flexible, and depend on the number of lines of the text.
 
Upvote 0

joseluis

Active Member
Licensed User
Longtime User
Hohoho!! :icon_clap: That is exactly what I needed, yes! It works! Thank you very much :sign0098:
 
Upvote 0
Top