Label.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. 
  2. using System;
  3. namespace Terminal {
  4. public enum TextAlignment {
  5. Left, Right, Centered, Justified
  6. }
  7. /// <summary>
  8. /// Label widget, displays a string at a given position, can include multiple lines.
  9. /// </summary>
  10. public class Label : View {
  11. string text;
  12. TextAlignment textAlignment;
  13. static Rect CalcRect (int x, int y, string s)
  14. {
  15. int mw = 0;
  16. int ml = 1;
  17. int cols = 0;
  18. foreach (var c in s) {
  19. if (c == '\n'){
  20. ml++;
  21. if (cols > mw)
  22. mw = cols;
  23. cols = 0;
  24. } else
  25. cols++;
  26. }
  27. return new Rect (x, y, cols, ml);
  28. }
  29. /// <summary>
  30. /// Public constructor: creates a label at the given
  31. /// coordinate with the given string, computes the bounding box
  32. /// based on the size of the string, assumes that the string contains
  33. /// newlines for multiple lines, no special breaking rules are used.
  34. /// </summary>
  35. public Label (int x, int y, string text) : this (CalcRect (x, y, text), text)
  36. {
  37. }
  38. /// <summary>
  39. /// Public constructor: creates a label at the given
  40. /// coordinate with the given string and uses the specified
  41. /// frame for the string.
  42. /// </summary>
  43. public Label (Rect rect, string text) : base (rect)
  44. {
  45. this.text = text;
  46. }
  47. public override void Redraw ()
  48. {
  49. if (TextColor != -1)
  50. Driver.SetColor (TextColor);
  51. else
  52. Driver.SetColor(Colors.Base.Normal);
  53. Clear ();
  54. Move (Frame.X, Frame.Y);
  55. Driver.AddStr (text);
  56. }
  57. /// <summary>
  58. /// The text displayed by this widget.
  59. /// </summary>
  60. public virtual string Text {
  61. get => text;
  62. set {
  63. text = value;
  64. SetNeedsDisplay ();
  65. }
  66. }
  67. public TextAlignment TextAlignment {
  68. get => textAlignment;
  69. set {
  70. textAlignment = value;
  71. SetNeedsDisplay ();
  72. }
  73. }
  74. /// <summary>
  75. /// The color used for the label
  76. /// </summary>
  77. Color textColor = -1;
  78. public Color TextColor {
  79. get => textColor;
  80. set {
  81. textColor = value;
  82. SetNeedsDisplay ();
  83. }
  84. }
  85. }
  86. }