using System.Collections.Generic; using Godot; namespace TBL.GodotSharp.Ui.AutoAdaption { /// /// 自适应 Ui 框架 /// public class AutoAdaptionUiRoot : Control { /// /// 注册的实例 /// private static readonly HashSet Instances = new HashSet(); /// /// 自适应比例值 /// private static float _adaptionShrink = 1.0f; /// /// 自适应比例 /// public static float AdaptionShrink { get => _adaptionShrink; set { _adaptionShrink = value; foreach (var instance in Instances) { instance._OnAutoScaleShrinkChanged(_adaptionShrink); } } } #region Node public override void _EnterTree() { Instances.Add(this); Connect("visibility_changed", this, "_OnVisibilityChanged"); } public override void _ExitTree() { Instances.Remove(this); } #endregion /// /// 可见性变更事件 /// protected void _OnVisibilityChanged() { if (Visible) { _OnAutoScaleShrinkChanged(AdaptionShrink); } } /// /// 自动调整缩放事件 /// protected void _OnAutoScaleShrinkChanged(float shrink) { if (!Visible) return; var size = GetViewport().Size * Vector2.One / shrink; if (IsSetAsToplevel()) { MarginRight = size.x * 0.5f; MarginBottom = size.y * 0.5f; MarginTop = size.y * -0.5f; MarginLeft = size.x * -0.5f; RectScale = Vector2.One * shrink; RectPosition = Vector2.Zero; } else { MarginTop = size.y * -0.5f; MarginLeft = size.x * -0.5f; MarginRight = size.x * 0.5f; MarginBottom = size.y * 0.5f; RectPivotOffset = size * 0.5f; RectScale = Vector2.One * shrink; } Update(); } } }