SFML community forums

Help => Graphics => Topic started by: dabo on July 29, 2008, 09:19:47 pm

Title: Splitting up text
Post by: dabo on July 29, 2008, 09:19:47 pm
Hi, this isen't a specific sfml question, but here it comes.

Let's say I want to display a bunch of text, but the text is not allowed to be wider than say 400px, which means I need to insert line breaks somehow. How would you solve this? I know how it could be done but I figure it would be really slow.
Title: Splitting up text
Post by: remi.k2620 on July 29, 2008, 09:44:02 pm
I think you'll have to use the method GetRect to know the width of the string, or wait a bit : in the roadmap there is "Add functions in sf::Font / sf::String to get the size of single characters"

In python you could do :
Code: [Select]
from PySFML import sf

text = 'Seconds before the Earth is demolished to make way for a galactic freeway, Arthur Dent is plucked off the planet by his friend Ford Prefect, a researcher for the revised edition of The Hitchhiker\'s Guide to the Galaxy who, for the last fifteen years, has been posing as an out-of-work actor.'

res = ''
newline = ''
s = sf.String()
for word in text.split(' '):
s.SetText(newline+word)
if s.GetRect().GetWidth() > 400:
res = res + '\n' + newline
newline = word
else:
newline = newline + ' ' + word

res = res[2:] + '\n' + newline

s.SetText(res)
# draw s...
Title: Splitting up text
Post by: dabo on July 29, 2008, 10:00:35 pm
Thanks, that's the way I was thinking about but I was afraid it would be slow, but maybe it's not.
Title: Splitting up text
Post by: remi.k2620 on July 29, 2008, 10:11:11 pm
It took 16 secondes to do it 1000 times, I don't know if it gives you an idea :/
Title: Splitting up text
Post by: dabo on July 29, 2008, 11:54:14 pm
Ok good, I came up with an algorithm that is fast enough, I guess I underestimated sfml :)