views:

150

answers:

3

I am now facing a problem with getting a string that fits the provided width in pixels.

For example, if I have a sentence like this (in JavaScript):

var mystring = "This is my sentence, I need to get just 50 pixels from it."

If I use the MeasureString method in C# I can get the width:

Font font = new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point);
SizeF size = graphics.MeasureString(mystring, font);

Let's say the width of this string is 400px but the max width I can display on the site is 50px.

If I shorten the string and measure it until it's less than 50px width it works, but it will require many iterations which is not a good solution at all.

Does anyone have a good solution for this?

Thanks.

A: 

Using a binary search for the optimal length it shouldn't take many iterations. Given the intricacies of text rendering, I believe that's the best you can do. You can't just take a width for each char and add them together.

Jon Skeet
A: 

You can approximate the width of a string as being the sum of the width of sub-strings. If your substrings are bounded by whitespace† it may even be a pretty good approximation. But you can't know until you ask exactly how wide any particular string will be, because the text rendering engine does things like kerning (altering the spacing between characters).

† and you probably want them to be, at least in a European language, because it is much easier to read text broken only on whitespace than text broken mid-word, even if it results in the text looking slightly more ragged.

tialaramex
+1  A: 

I would like to add to this section - "If I shorten the string and measure it until it's less than 50px width ..."

Why don't you do a binary search starting from the middle of the string. Here's the location for starters. No matter how long the string is - it will take much lesser time to find out what's your ideal length. The complexity reduces to log(n) from n.

For better results, you can truncate your string if it's really long, like 500 characters, for example, before starting your binary search.

BrainCracker