label.d 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. module renderable.label;
  2. import color;
  3. import vector;
  4. import cell;
  5. import renderable.renderable;
  6. import horizontaltextalignment;
  7. import verticaltextalignment;
  8. import renderable.rect;
  9. import std.stdio;
  10. class Label : Renderable {
  11. Rect rect;
  12. string text;
  13. HorizontalTextAlignment horizontalTextAlignment;
  14. VerticalTextAlignment verticalTextAlignment;
  15. Color color;
  16. this(Rect rect, string text, VerticalTextAlignment verticalTextAlignment, Color color = Color.terminal()) {
  17. this(rect, text, HorizontalTextAlignment.center, verticalTextAlignment, color);
  18. }
  19. this(Rect rect, string text, HorizontalTextAlignment horizontalTextAlignment, Color color = Color.terminal()) {
  20. this(rect, text, horizontalTextAlignment, VerticalTextAlignment.center, color);
  21. }
  22. this(Rect rect, string text, Color color) {
  23. this(rect, text, HorizontalTextAlignment.center, VerticalTextAlignment.center, color);
  24. }
  25. this(Rect rect, string text, HorizontalTextAlignment horizontalTextAlignment = HorizontalTextAlignment.center, VerticalTextAlignment verticalTextAlignment = VerticalTextAlignment.center, Color color = Color.terminal()) {
  26. this.dimension = rect.dimension;
  27. this.rect = rect;
  28. this.text = text;
  29. this.color = color;
  30. this.horizontalTextAlignment = horizontalTextAlignment;
  31. this.verticalTextAlignment = verticalTextAlignment;
  32. }
  33. override Cell[] render() {
  34. Cell[] cells;
  35. int pos = 0;
  36. foreach (dchar character; text) {
  37. long x;
  38. long y;
  39. if (horizontalTextAlignment == HorizontalTextAlignment.center) {
  40. x = ((dimension.x / 2) - (text.length / 2)) + pos;
  41. } else if (horizontalTextAlignment == HorizontalTextAlignment.left) {
  42. x = pos;
  43. } else if (horizontalTextAlignment == HorizontalTextAlignment.right) {
  44. x = (dimension.x - text.length) + pos;
  45. }
  46. if (verticalTextAlignment == VerticalTextAlignment.center) {
  47. y = dimension.y / 2;
  48. } else if (verticalTextAlignment == VerticalTextAlignment.top) {
  49. y = 0;
  50. } else if (verticalTextAlignment == VerticalTextAlignment.bottom) {
  51. y = dimension.y - 1;
  52. }
  53. cells ~= Cell(Vector(cast(int)x, cast(int)y), character, color);
  54. ++pos;
  55. }
  56. cells ~= rect.render();
  57. return cells;
  58. }
  59. }