label.dart 1.51 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
part of flutter_sprites;
6

7
/// Labels are used to display a string of text in a the node tree. To align
8
/// the label, the textAlign property of the [TextStyle] can be set.
9
class Label extends Node {
10 11 12 13 14 15
  /// Creates a new Label with the provided [text] and [textStyle].
  Label(this._text, {
    TextStyle textStyle,
    TextAlign textAlign
  }) : _textStyle = textStyle ?? const TextStyle(),
       textAlign = textAlign ?? TextAlign.left;
16

17
  /// The text being drawn by the label.
18
  String get text => _text;
19
  String _text;
20
  set text(String text) {
21 22 23 24
    _text = text;
    _painter = null;
  }

25
  /// The style to draw the text in.
26
  TextStyle get textStyle => _textStyle;
27
  TextStyle _textStyle;
28
  set textStyle(TextStyle textStyle) {
29 30 31 32
    _textStyle = textStyle;
    _painter = null;
  }

33 34 35
  /// How the text should be aligned horizontally.
  TextAlign textAlign;

36 37 38
  TextPainter _painter;
  double _width;

39
  @override
Adam Barth's avatar
Adam Barth committed
40
  void paint(Canvas canvas) {
41
    if (_painter == null) {
42
      _painter = new TextPainter(text: new TextSpan(style: _textStyle, text: _text))
43
        ..layout();
44
      _width = _painter.size.width;
45 46 47
    }

    Offset offset = Offset.zero;
48
    if (textAlign == TextAlign.center) {
49
      offset = new Offset(-_width / 2.0, 0.0);
50
    } else if (textAlign == TextAlign.right) {
51
      offset = new Offset(-_width, 0.0);
52 53 54 55 56
    }

    _painter.paint(canvas, offset);
  }
}