TextAnnotation.cs 2.4 KB

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