SFML community forums
General => General discussions => Topic started by: ErikPerik on September 19, 2010, 07:32:18 pm
-
I am currently writing a menusystem for a game I'm making, and want to be able to dynamically add text to a container. The string will be a paragraph of text. So my question is how do I calculate where to add the newline for a new row if the string is about to overflow from its container?
On way would be to know how many characters one row should fill, and add the newline accordingly. Another option would be to add get the position of a character that is outside of the containers limits, and add the newline there, using sf::String::GetCharacterPos (http://www.sfml-dev.org/documentation/1.6/classsf_1_1String.htm#d471fee3d4dda7fefb9ff610d049f210). What do you guys (and gals) think?
For example:
(http://i.imgur.com/KXl5J.png)
-
I used this system :
- Each time you modify the std::string of the object, the object calculate its sf::String
- The calculation of the sf::String is based on its container.
- For each word of the std::string, get the size of the word, add it to the actual line size. If this is larger than the container, add a new line in the sf::string. Add the word to the sf::string.
This is fast, and the calculation is made only on modifications. By the way, you are keeping your std::string exactly like you typed it (for example you can have choosen to add a new line).
-
I think I get it, you mean like this psuedocode:
def set_string(self, str):
words = str.split(' ');
text = ''
current_width = 0
for words in word:
word_size = sf.String(word).GetRect()
# ...
# turn rect into size object with width/height-members
# ...
# if it overflows
if current_width + word_size.width > self.container.width:
text += '\n' + word
current_width = 0
# it didn't, just add it without line break
else:
text += ' ' + word
current_width += word_size.width
# create an sf.String from text
self.sprite = sf.String(text)
I'm writing my game in C++ so this psuedocode is not to be considered a working example. But did I get the point right? The idea is simple and pretty damn smart.
-
Right, but :
- When you put a newline, current_width must be reseted to word size, not 0
- When you add the word, don't forget to add the space size too (I calculate it once at the beginning)