1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using System.Collections.Generic;
- using Godot;
- namespace TBL.GodotSharp.Ui.AutoAdaption
- {
- /// <summary>
- /// 自适应 Ui 框架
- /// </summary>
- public class AutoAdaptionUiRoot : Control
- {
- /// <summary>
- /// 注册的实例
- /// </summary>
- private static readonly HashSet<AutoAdaptionUiRoot> Instances = new HashSet<AutoAdaptionUiRoot>();
- /// <summary>
- /// 自适应比例值
- /// </summary>
- private static float _adaptionShrink = 1.0f;
- /// <summary>
- /// 自适应比例
- /// </summary>
- 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
- /// <summary>
- /// 可见性变更事件
- /// </summary>
- protected void _OnVisibilityChanged()
- {
- if (Visible)
- {
- _OnAutoScaleShrinkChanged(AdaptionShrink);
- }
- }
- /// <summary>
- /// 自动调整缩放事件
- /// </summary>
- 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();
- }
- }
- }
|