Game Maker Games, Articles, Tutorials & More

Game Maker Network


Howdy, Guest! Please sign in or register an account.

Print

draw_text_wordwrapped

By Daniel · December 25, 2008

An efficient method for drawing multiple lines of text with word wrapping. The arguments are identical to those used in draw_text_ext.

// draw_text_wordwrapped(x, y, string, sep, w)
// An efficient method for drawing multiple lines of text with word wrapping
// The arguments are identical to those used in draw_text_ext

var in, out, w, n_floor, n_ceil, n_mid, n;
in = argument2;
out = '';
w = argument4;

while (string_length(in)) {
  // Determine how many characters may fit on the next line via binary search
  // n_floor is the (eventually largest) number that works; n_ceil is the
  // (eventually smallest) number that does not.
  n_floor = 1;
  n_ceil = string_length(in) + 1;
  while (n_ceil - n_floor > 1) {
    n_mid = (n_ceil + n_floor) div 2;
    if (string_width(string_copy(in, 1, n_mid)) > w) // doesn't fit; too large
      n_ceil = n_mid;
    else // does fit
      n_floor = n_mid;
  }
  
  // Search backward until whitespace is encountered
  n = n_floor;
  if (n < string_length(in)) {
    while (string_char_at(in, n) != ' ' && string_char_at(in, n + 1) != ' ') {
      n -= 1;
      if (n == 0) {
        // Force line break within a word (no other good option)
        n = n_floor;
        break;
      }
    }
  }
  
  // Move this line from the input string to the output string
  out += string_copy(in, 1, n) + '#';
  in = string_delete(in, 1, n);
}

// Draw the result
draw_text_ext(argument0, argument1, out, argument3, w);

Comments

There are no comments to display.

Post a Comment

You must be signed in to post comments.

Advertisement