text method

void text(
  1. String text,
  2. double x,
  3. double y
)

Paint the given text at the given (x,y), using the current horizontal and vertical text alignment and text size.

Implementation

void text(String text, double x, double y) {
  final paragraphBuilder = ParagraphBuilder(ParagraphStyle(
    fontFamily: _fontName,
    fontSize: _fontSize,
    textAlign: _textAlignHorizontal.toFlutterAlign(),
  ))
    ..pushStyle(TextStyle(
      color: _paintingContext.fillPaint.color,
      height: _textLeading != null ? _textLeading! / _fontSize : null,
    ))
    ..addText(text);
  final paragraph = paragraphBuilder.build()
    ..layout(
      ParagraphConstraints(width: double.infinity),
    );

  late double textX;
  late double textY;
  switch (_textAlignHorizontal) {
    case TextAlignHorizontal.left:
      textX = x;
      break;
    case TextAlignHorizontal.center:
      textX = x - (paragraph.maxIntrinsicWidth / 2);
      break;
    case TextAlignHorizontal.right:
      textX = x - paragraph.maxIntrinsicWidth;
      break;
  }

  switch (_textAlignVertical) {
    case TextAlignVertical.top:
      // We adjust the top alignment to deal with leading. Flutter applies extra
      // leading to the first line of text, but Processing wants the top of the
      // first line to sit exactly on the given `y` value. We do our best to
      // correct for that, here.
      final firstCharacterHeight = paragraph.getBoxesForRange(0, 1).first.toRect().height;
      final leadingAdjustment = _textLeading != null ? (_textLeading! - firstCharacterHeight) : 0;

      textY = y - leadingAdjustment;
      break;
    case TextAlignVertical.center:
      textY = y - (paragraph.height / 2);
      break;
    case TextAlignVertical.baseline:
      textY = y - paragraph.alphabeticBaseline;
      break;
    case TextAlignVertical.bottom:
      textY = y - paragraph.height;
      break;
  }

  _paintingContext.canvas.drawParagraph(paragraph, Offset(textX, textY));
}