I have some text which I want to display in some sort of log at the bottom of the game.
I want a way of ensuring that the text fits in a particular size, and if its over that size, I'll trim it myself ("bla bla bl...")
I know that I can obtain the size that the text will take by using SpriteFont.MeasureString - so I know whether a particular string will overshoot the limit.
The most obvious solution involves a loop of this sort
StringBuilder display = new StringBuilder();
foreach (char c in string)
{
if mySpriteFont.MeasureString((display.Append(c)) > SOMEAMOUNT
{
display.append("...");
return display.toString();
}
}
However I'm afraid that this sort of thing is very expensive to do. Any other solutions?
You're going to have to use MeasureString in there somewhere, it's just a case of the algorithm you use. The naiive solution is to just crop one character off the end until the string fits. A better one that has been suggested is to crop it in half, see if it fits, and home in on the solution that way. An alternative would measure the string length once, and then take an approximation based on the proportion of the string that is outside the boundaries. For example, if your limit is 100 pixels, and you have a string that is 400 pixels wide, crop of the last 3/4 of the string (in characters). Then, revert to the "factor of 2" approach, by removing or adding half the approximated string, and recursing until you are within one character. This should be fast enough for most occasions, and the approximation stage may well remove an initial overhead, particularly if your string is long, and in some cases may prove to give a result immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With