drawText method

Point<num> drawText(
  1. BitmapFont font,
  2. String text, {
  3. dynamic x = 0.0,
  4. dynamic y = 0.0,
  5. dynamic alignX = 0.0,
  6. dynamic alignY = 0.0,
  7. dynamic scaleX = 1.0,
  8. dynamic scaleY = 1.0,
  9. dynamic alignXByLine = true,
  10. ColorList? colors,
})

Draws text using the specified BitmapFont and rendering parameters.

  • font: The BitmapFont to use for rendering.
  • text: The string to draw. Supports newline characters (\n).
  • x, y: The base coordinates for drawing the text. Defaults to (0,0). How these are interpreted depends on alignX and alignY.
  • alignX: Horizontal alignment. 0.0 for left, 0.5 for center, 1.0 for right. Defaults to 0.0.
  • alignY: Vertical alignment. 0.0 for top, 0.5 for middle, 1.0 for bottom. Defaults to 0.0.
  • scaleX, scaleY: Scaling factors for the rendered text. Defaults to 1.0.
  • alignXByLine: If true (default), horizontal alignment is applied per line. If false, it's applied to the entire text block based on the widest line.
  • colors: An optional ColorList. If provided, colors[0] tints the entire text.

Returns a Point representing the width and height of the drawn text block, after scaling.

Implementation

Point drawText(
  BitmapFont font,
  String text, {
  x = 0.0,
  y = 0.0,
  alignX = 0.0,
  alignY = 0.0,
  scaleX = 1.0,
  scaleY = 1.0,
  alignXByLine = true,
  ColorList? colors,
}) {
  var lines = text.split("\n");
  var h = font.leading * lines.length * scaleY;
  var w = measureText(font, text).x * scaleX;
  var startX = x;
  var startY = y;

  pushMatrix();
  translate(x - w * alignX, y - h * alignY);
  x = 0.0;
  y = 0.0;

  for (var line in lines) {
    if (alignXByLine) {
      popMatrix();
      w = measureText(font, line).x * scaleX;

      pushMatrix();
      translate(startX - w * alignX, startY - h * alignY);
    }
    for (int charCode in line.runes) {
      var glyph = font.glyphs[charCode];
      if (glyph != null) {
        if (glyph.image != null) {
          drawImage([glyph.image!], 0, x, y, 0, scaleX, scaleY, colors);
        }
        x += glyph.advance * font.tracking * scaleX;
      }
    }
    y += font.leading * scaleY;
    x = 0;
  }
  popMatrix();
  return Point(w, h);
}