drawString function

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

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

Image drawString(Image image, BitmapFont font, int x, int y, String string,
    {int color = 0xffffffff}) {
  if (color != 0xffffffff) {
    var ca = getAlpha(color);
    if (ca == 0) {
      return image;
    }
    num da = ca / 255.0;
    num dr = getRed(color) / 255.0;
    num dg = getGreen(color) / 255.0;
    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();
    }
  }

  var chars = string.codeUnits;
  for (var c in chars) {
    if (!font.characters.containsKey(c)) {
      x += font.base ~/ 2;
      continue;
    }

    var ch = font.characters[c];

    var x2 = x + ch.width;
    var 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;
  }

  return image;
}