AutoAdaptionUiRoot.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Collections.Generic;
  2. using Godot;
  3. namespace TBL.GodotSharp.Ui.AutoAdaption
  4. {
  5. /// <summary>
  6. /// 自适应 Ui 框架
  7. /// </summary>
  8. public class AutoAdaptionUiRoot : Control
  9. {
  10. /// <summary>
  11. /// 注册的实例
  12. /// </summary>
  13. private static readonly HashSet<AutoAdaptionUiRoot> Instances = new HashSet<AutoAdaptionUiRoot>();
  14. /// <summary>
  15. /// 自适应比例值
  16. /// </summary>
  17. private static float _adaptionShrink = 1.0f;
  18. /// <summary>
  19. /// 自适应比例
  20. /// </summary>
  21. public static float AdaptionShrink
  22. {
  23. get => _adaptionShrink;
  24. set
  25. {
  26. _adaptionShrink = value;
  27. foreach (var instance in Instances)
  28. {
  29. instance._OnAutoScaleShrinkChanged(_adaptionShrink);
  30. }
  31. }
  32. }
  33. #region Node
  34. public override void _EnterTree()
  35. {
  36. Instances.Add(this);
  37. Connect("visibility_changed", this, "_OnVisibilityChanged");
  38. }
  39. public override void _ExitTree()
  40. {
  41. Instances.Remove(this);
  42. }
  43. #endregion
  44. /// <summary>
  45. /// 可见性变更事件
  46. /// </summary>
  47. protected void _OnVisibilityChanged()
  48. {
  49. if (Visible)
  50. {
  51. _OnAutoScaleShrinkChanged(AdaptionShrink);
  52. }
  53. }
  54. /// <summary>
  55. /// 自动调整缩放事件
  56. /// </summary>
  57. protected void _OnAutoScaleShrinkChanged(float shrink)
  58. {
  59. if (!Visible) return;
  60. var size = GetViewport().Size * Vector2.One / shrink;
  61. if (IsSetAsToplevel())
  62. {
  63. MarginRight = size.x * 0.5f;
  64. MarginBottom = size.y * 0.5f;
  65. MarginTop = size.y * -0.5f;
  66. MarginLeft = size.x * -0.5f;
  67. RectScale = Vector2.One * shrink;
  68. RectPosition = Vector2.Zero;
  69. }
  70. else
  71. {
  72. MarginTop = size.y * -0.5f;
  73. MarginLeft = size.x * -0.5f;
  74. MarginRight = size.x * 0.5f;
  75. MarginBottom = size.y * 0.5f;
  76. RectPivotOffset = size * 0.5f;
  77. RectScale = Vector2.One * shrink;
  78. }
  79. Update();
  80. }
  81. }
  82. }