using System; using Godot; namespace TBL.GodotSharp.Ui.AutoAdaption { /// /// 自动自适应控制器 /// 控制所有的 /// public class AutoAdaptionController : Node { /// /// 设计 Ui 尺寸 /// [Export] public Vector2 DesignSize; /// /// 自动缩放 Ui 开关 /// [Export] private bool _autoScaleUi; /// /// 世界视图缩放值 /// private int _worldViewScale = 1; /// /// 自动 Ui 缩放值 /// private float _autoScaleShrink = 1.0f; /// /// 是否启用自动 Ui 调节 /// public bool AutoScaleUi { get => _autoScaleUi; set { _autoScaleUi = value; var winSize = OS.WindowSize; var minSize = DesignSize; if (winSize.x < winSize.y) { minSize.y = minSize.x; } else { minSize.x = minSize.y; } if (_autoScaleUi) { var d = 1; if (winSize.x < winSize.y) d = 0; _autoScaleShrink = Mathf.Max(1.0f, Mathf.Floor(winSize[d] / minSize[d])); } else { _autoScaleShrink = 1.0f; } GetTree().SetScreenStretch(SceneTree.StretchMode.Disabled, SceneTree.StretchAspect.Expand, minSize); AutoAdaptionUiRoot.AdaptionShrink = _autoScaleShrink; if (_autoScaleUi) { WorldViewScale = Mathf.RoundToInt(_autoScaleShrink); } else { WorldViewScale = 1; } } } /// /// 世界视图缩放率 /// public int WorldViewScale { get => Mathf.Max(1, _worldViewScale); set { _worldViewScale = value; // TODO: 世界视图 // WorldViewContainer.WorldViewShrink = WorldViewScale; } } /// /// 自动 Ui 缩放率 /// public float AutoScaleShrink => _autoScaleShrink; /// /// 屏幕尺寸变化事件 /// protected void _OnScreenResized() { AutoScaleUi = _autoScaleUi; WorldViewScale = _worldViewScale; } #region Node public override async void _EnterTree() { var tree = GetTree(); if (DesignSize == Vector2.Zero) DesignSize = new Vector2( Convert.ToSingle(ProjectSettings.GetSetting("display/window/size/width")), Convert.ToSingle(ProjectSettings.GetSetting("display/window/size/height")) ); AutoScaleUi = _autoScaleUi; WorldViewScale = _worldViewScale; Name = nameof(AutoAdaptionController); tree.Connect("screen_resized", this, nameof(_OnScreenResized)); await ToSignal(tree, "idle_frame"); tree.EmitSignal("screen_resized"); } public override void _ExitTree() { AutoScaleUi = _autoScaleUi; WorldViewScale = _worldViewScale; } #endregion /// /// 设置控件为填满设计尺寸 /// public void SetFullParentDesignSize(Control target) { target.AnchorLeft = target.AnchorTop = 0.5f; target.AnchorRight = target.AnchorBottom = 0.5f; target.MarginLeft = DesignSize.x * -0.5f; target.MarginRight = DesignSize.x * 0.5f; target.MarginTop = DesignSize.x * -0.5f; target.MarginBottom = DesignSize.x * 0.5f; } } }