label.dart 1.54 KB
Newer Older
1
part of flutter_sprites;
2

3
/// Labels are used to display a string of text in a the node tree. To align
4
/// the label, the textAlign property of the [TextStyle] can be set.
5
class Label extends Node {
6
  /// Creates a new Label with the provided [_text] and [_textStyle].
7 8 9 10 11 12 13 14
  Label(this._text, [this._textStyle]) {
    if (_textStyle == null) {
      _textStyle = new TextStyle();
    }
  }

  String _text;

15
  /// The text being drawn by the label.
16 17 18 19 20 21 22 23 24
  String get text => _text;

  set text(String text) {
    _text = text;
    _painter = null;
  }

  TextStyle _textStyle;

25
  /// The style to draw the text in.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  TextStyle get textStyle => _textStyle;

  set textStyle(TextStyle textStyle) {
    _textStyle = textStyle;
    _painter = null;
  }

  TextPainter _painter;
  double _width;

  void paint(PaintingCanvas canvas) {
    if (_painter == null) {
      PlainTextSpan textSpan = new PlainTextSpan(_text);
      StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, [textSpan]);
      _painter = new TextPainter(styledTextSpan);

42 43
      _painter.maxWidth = double.INFINITY;
      _painter.minWidth = 0.0;
44 45
      _painter.layout();

46 47 48 49 50
      _width = _painter.maxContentWidth.ceil().toDouble();

      _painter.maxWidth = _width;
      _painter.minWidth = _width;
      _painter.layout();
51 52 53 54
    }

    Offset offset = Offset.zero;
    if (_textStyle.textAlign == TextAlign.center) {
55
      offset = new Offset(-_width / 2.0, 0.0);
56
    } else if (_textStyle.textAlign == TextAlign.right) {
57
      offset = new Offset(-_width, 0.0);
58 59 60 61 62
    }

    _painter.paint(canvas, offset);
  }
}