drawStringWrap function

Image drawStringWrap(
  1. Image image,
  2. BitmapFont font,
  3. int x,
  4. int y,
  5. String string, {
  6. int color = 0xffffffff,
})

Same as drawString except the strings will wrap around to create multiple lines. You can load your own font, or use one of the existing ones such as: arial_14, arial_24, or arial_48.

Implementation

Image drawStringWrap(Image image, BitmapFont font, int x, int y, String string,
    {int color = 0xffffffff}) {

  var stringHeight = findStringHeight(font, string);
  var words = string.split(new RegExp(r"\s+"));
  var subString = "";
  var x2 = x;

  for (var w in words) {
    final ws = StringBuffer();
    ws.write(w);
    ws.write(' ');
    w = ws.toString();
    final chars = w.codeUnits;
    var wordWidth = 0;
    for (var c in chars) {
      if (!font.characters.containsKey(c)) {
        wordWidth += font.base ~/ 2;
        continue;
      }
      final ch = font.characters[c]!;
      wordWidth += ch.xadvance;
    }
    if ((x2 + wordWidth) > image.width) {
      // If there is a word that won't fit the starting x, stop drawing
      if ((x == x2) || (x + wordWidth > image.width)) {
        return image;
      }

      drawString(image, font, x, y, subString, color: color);

      subString = "";
      x2 = x;
      y += stringHeight;
      subString += w;
      x2 += wordWidth;
    } else {
      subString += w;
      x2 += wordWidth;
    }

    if (subString.length > 0) {
      drawString(image, font, x, y, subString, color: color);
    }
  }

  return image;
}