TextAnnotation.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. namespace Terminal.Gui.Views;
  2. /// <summary>Displays text at a given position (in screen space or graph space)</summary>
  3. public class TextAnnotation : IAnnotation
  4. {
  5. /// <summary>
  6. /// The location in graph space to draw the <see cref="Text"/>. This annotation will only show if the point is in
  7. /// the current viewable area of the graph presented in the <see cref="GraphView"/>
  8. /// </summary>
  9. public PointF GraphPosition { get; set; }
  10. /// <summary>
  11. /// The location on screen to draw the <see cref="Text"/> regardless of scroll/zoom settings. This overrides
  12. /// <see cref="GraphPosition"/> if specified.
  13. /// </summary>
  14. public Point? ScreenPosition { get; set; }
  15. /// <summary>Text to display on the graph</summary>
  16. public string Text { get; set; }
  17. /// <summary>True to add text before plotting series. Defaults to false</summary>
  18. public bool BeforeSeries { get; set; }
  19. /// <summary>Draws the annotation</summary>
  20. /// <param name="graph"></param>
  21. public void Render (GraphView graph)
  22. {
  23. if (ScreenPosition.HasValue)
  24. {
  25. DrawText (graph, ScreenPosition.Value.X, ScreenPosition.Value.Y);
  26. return;
  27. }
  28. Point screenPos = graph.GraphSpaceToScreen (GraphPosition);
  29. DrawText (graph, screenPos.X, screenPos.Y);
  30. }
  31. /// <summary>
  32. /// Draws the <see cref="Text"/> at the given coordinates with truncation to avoid spilling over
  33. /// <see name="View.Viewport"/> of the <paramref name="graph"/>
  34. /// </summary>
  35. /// <param name="graph"></param>
  36. /// <param name="x">Screen x position to start drawing string</param>
  37. /// <param name="y">Screen y position to start drawing string</param>
  38. protected void DrawText (GraphView graph, int x, int y)
  39. {
  40. // the draw point is out of control bounds
  41. if (!graph.Viewport.Contains (new Point (x, y)))
  42. {
  43. return;
  44. }
  45. // There is no text to draw
  46. if (string.IsNullOrWhiteSpace (Text))
  47. {
  48. return;
  49. }
  50. graph.Move (x, y);
  51. int availableWidth = graph.Viewport.Width - x;
  52. if (availableWidth <= 0)
  53. {
  54. return;
  55. }
  56. if (Text.Length < availableWidth)
  57. {
  58. graph.AddStr (Text);
  59. }
  60. else
  61. {
  62. graph.AddStr (Text.Substring (0, availableWidth));
  63. }
  64. }
  65. }