TextRenderItem.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Windows.Forms;
  6. using NTERA.Core;
  7. using NTERA.Core.Interop;
  8. namespace NTERA.Console.RenderItem
  9. {
  10. public class TextRenderItem : BaseRenderItem
  11. {
  12. public Font Font { get; set; } = new Font("MS UI Gothic", 12);
  13. public SolidBrush TextBrush { get; set; } = new SolidBrush(Color.White);
  14. public string Text { get; set; }
  15. public DisplayLineAlignment Alignment { get; set; }
  16. public PrintFlags Flags { get; set; }
  17. private static readonly string[] FullwidthCharacters = "0123456789。".ToCharArray().Select(x => x.ToString()).ToArray();
  18. private static string AlignText(string input)
  19. {
  20. foreach (var num in FullwidthCharacters)
  21. {
  22. input = input.Replace(num, $" {num}");
  23. }
  24. return input.Replace(" ", "   ");
  25. }
  26. public TextRenderItem(string text, DisplayLineAlignment alignment = DisplayLineAlignment.LEFT, Color? color = null)
  27. {
  28. Text = AlignText(text); //text.Replace(" ", "   ").Replace("6", " 6"); //" 6   ", " 6  "
  29. Alignment = alignment;
  30. if (color.HasValue)
  31. TextBrush = new SolidBrush(color.Value);
  32. }
  33. public override int Render(Graphics graphics, Rectangle renderArea, Rectangle invalidatedArea, Point mousePointer)
  34. {
  35. int width = (int)graphics.MeasureString(Text, Font).Width;
  36. int x;
  37. switch (Alignment)
  38. {
  39. default:
  40. case DisplayLineAlignment.LEFT:
  41. x = renderArea.X;
  42. break;
  43. case DisplayLineAlignment.CENTER:
  44. x = (renderArea.Width - width) / 2;
  45. break;
  46. case DisplayLineAlignment.RIGHT:
  47. x = renderArea.Width - width;
  48. break;
  49. }
  50. //graphics.DrawString(Text, Font, TextBrush, x, renderArea.Y);
  51. //return x + width;
  52. var point = new Point(x, renderArea.Y);
  53. var textFormatFlags = TextFormatFlags.ExpandTabs;
  54. if (!Flags.SingleLine) {
  55. // We want word wrapping
  56. textFormatFlags |= TextFormatFlags.WordBreak;
  57. // FIXME: We will need to make a rectangle, not a point,
  58. // to draw the text in
  59. }
  60. TextRenderer.DrawText(graphics, Text, Font, point, TextBrush.Color, textFormatFlags);
  61. return TextRenderer.MeasureText(graphics, Text, Font).Width + renderArea.X;
  62. }
  63. public static List<TextRenderItem> CreateFromLinedText(string text)
  64. {
  65. List<TextRenderItem> items = new List<TextRenderItem>();
  66. foreach (string line in text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
  67. {
  68. items.Add(new TextRenderItem(line));
  69. }
  70. return items;
  71. }
  72. }
  73. }