drawString function

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

Draw a string horizontally into image horizontally into image at position x,y with the given color.

You can load your own font, or use one of the existing ones such as: arial_14, arial_24, or arial_48.

Implementation

//  Fonts can be create with a tool such as: https://ttf2fnt.com/
Image drawString(Image image, BitmapFont font, int x, int y, String string,
    {int color = 0xffffffff, bool rightJustify = false}) {
  if (color != 0xffffffff) {
    final ca = getAlpha(color);
    if (ca == 0) {
      return image;
    }
    final num da = ca / 255.0;
    final num dr = getRed(color) / 255.0;
    final num dg = getGreen(color) / 255.0;
    final num db = getBlue(color) / 255.0;
    for (var i = 1; i < 256; ++i) {
      _r_lut[i] = (dr * i).toInt();
      _g_lut[i] = (dg * i).toInt();
      _b_lut[i] = (db * i).toInt();
      _a_lut[i] = (da * i).toInt();
    }
  }

  final int stringHeight = findStringHeight(font, string);
  final int origX = x;
  final substrings = string.split(new RegExp(r"[(\n|\r)]"));

  for (var ss in substrings) {
    var chars = ss.codeUnits;
    if (rightJustify == true) {
      for (var c in chars) {
        if (!font.characters.containsKey(c)) {
          x -= font.base ~/ 2;
          continue;
        }

        final ch = font.characters[c]!;
        x -= ch.xadvance;
      }
    }
    for (var c in chars) {
      if (!font.characters.containsKey(c)) {
        x += font.base ~/ 2;
        continue;
      }

      final ch = font.characters[c]!;

      final x2 = x + ch.width;
      final y2 = y + ch.height;
      var pi = 0;
      for (var yi = y; yi < y2; ++yi) {
        for (var xi = x; xi < x2; ++xi) {
          var p = ch.image[pi++];
          if (color != 0xffffffff) {
            p = getColor(_r_lut[getRed(p)], _g_lut[getGreen(p)],
                _b_lut[getBlue(p)], _a_lut[getAlpha(p)]);
          }
          drawPixel(image, xi + ch.xoffset, yi + ch.yoffset, p);
        }
      }

      x += ch.xadvance;
    }
    y = y+stringHeight;
    x = origX;
  }

  return image;
}