[SDL] How to draw text in some determined area, doing auto wrap

nbs nbs at sonic.net
Thu Sep 5 14:32:01 PDT 2002


On Thu, Sep 05, 2002 at 02:19:03PM -0700, Charles Wardlaw wrote:
> >    PS: We use python+SDL and pygame. So solutions using them are
> > preferable :)
> 
> Well, the only real way to do this is manually by calculating how many
> characters can fit into a rectangle.  I'll tell you now: skip the TTF
> font stuff and use monospace bitmap fonts.  Non-monospace fonts require
> a bit more calculation.

Well, kinda.  If you use proportionally-spaced fonts, you can just use
SDL_TTF to render one word at a time:


  The
  quick
  brown
  fox.


For each word, examine whether we'll be going off the edge if we draw that
word at the current cursor position.  If not, draw the word, and move
the cursor's X position over that far.

If it will, first reset the cursor's X position to the left edge,
and move the cursor's Y position down one line.  THEN draw the word,
and move the cursor's X position over that far.


The one special case is when a SINGLE particular word is too long to
fit on one line:


  supercalifragolisticexpialadocious        [no idea how to spell that ;^) ]


In that case, you could have some 'special case' where it then draws the
word one letter at a time, and breaks it up when one of the LETTERS would
be past the right edge.



The difference between doing this 'one word at a time' word-wrap vs.
just blitting the entire word is how many times you blit.
(Once you've blit a word, you WILL end up using it, unless you've gone
below the _bottom_ boundary of where you want your text to go...
then you're just screwed! :) )



If you don't think your text will be longer than one line _most_ of the
time, you can just render it all as one sentence first:

  The quick brown fox.


If that's too wide to fit, THEN you try doing it one.. word.. at.. a.. time.


-bill!




More information about the SDL mailing list