TextObject.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Platform;
  4. using Avalonia.Controls.Shapes;
  5. using Avalonia.Layout;
  6. using Avalonia.Media;
  7. using Avalonia.Media.TextFormatting;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace InABox.Avalonia.Components.ImageEditing;
  15. internal class TextObject : IImageEditorObject
  16. {
  17. public IBrush? PrimaryBrush { get; set; }
  18. public Point Point { get; set; }
  19. public Size Size { get; set; }
  20. public string Text { get; set; } = "";
  21. private TextBlock Control = new();
  22. public Control GetControl() => Control;
  23. public void Update()
  24. {
  25. Canvas.SetLeft(Control, Point.X);
  26. Canvas.SetTop(Control, Point.Y);
  27. var font = new Typeface(Control.FontFamily);
  28. var formatted = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, font, 12, PrimaryBrush);
  29. var width = formatted.WidthIncludingTrailingWhitespace;
  30. var height = formatted.Height;
  31. if(Size.Width == 0)
  32. {
  33. Size = Size.WithWidth(width);
  34. }
  35. if(Size.Height == 0)
  36. {
  37. Size = Size.WithHeight(height);
  38. }
  39. var scaleFactor = Math.Min(Size.Width / width, Size.Height / height);
  40. Control.FontSize = 12 * scaleFactor;
  41. Control.Text = Text;
  42. Control.Foreground = PrimaryBrush;
  43. }
  44. public void SetActive(bool active)
  45. {
  46. }
  47. }