BetterContentSizeFitter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using UnityEngine;
  8. using UnityEngine.EventSystems;
  9. using UnityEngine.UI;
  10. namespace TheraBytes.BetterUi
  11. {
  12. #if UNITY_2018_3_OR_NEWER
  13. [ExecuteAlways]
  14. #else
  15. [ExecuteInEditMode]
  16. #endif
  17. [HelpURL("https://documentation.therabytes.de/better-ui/BetterContentSizeFitter.html")]
  18. [AddComponentMenu("Better UI/Layout/Better Content Size Fitter", 30)]
  19. public class BetterContentSizeFitter : ContentSizeFitter, IResolutionDependency, ILayoutChildDependency, ILayoutElement, ILayoutIgnorer
  20. {
  21. [Serializable]
  22. public class Settings : IScreenConfigConnection
  23. {
  24. public FitMode HorizontalFit;
  25. public FitMode VerticalFit;
  26. public bool IsAnimated;
  27. public float AnimationTime = 0.2f;
  28. public bool HasMinWidth;
  29. public bool HasMinHeight;
  30. public bool HasMaxWidth;
  31. public bool HasMaxHeight;
  32. [SerializeField]
  33. string screenConfigName;
  34. public string ScreenConfigName { get { return screenConfigName; } set { screenConfigName = value; } }
  35. }
  36. [Serializable]
  37. public class SettingsConfigCollection : SizeConfigCollection<Settings> { }
  38. RectTransform rectTransform { get { return this.transform as RectTransform; } }
  39. public Settings CurrentSettings { get { return customSettings.GetCurrentItem(settingsFallback); } }
  40. public RectTransform Source { get { return (source != null) ? source : this.rectTransform; } set { source = value; SetDirty(); } }
  41. public bool TreatAsLayoutElement { get { return treatAsLayoutElement; } set { treatAsLayoutElement = value; } }
  42. public FloatSizeModifier CurrentMinWidth { get { return minWidthSizers.GetCurrentItem(minWidthSizerFallback); } }
  43. public FloatSizeModifier CurrentMinHeight { get { return minHeightSizers.GetCurrentItem(minHeightSizerFallback); } }
  44. public FloatSizeModifier CurrentMaxWidth { get { return maxWidthSizers.GetCurrentItem(maxWidthSizerFallback); } }
  45. public Vector2SizeModifier CurrentPadding { get { return paddingSizers.GetCurrentItem(paddingFallback); } }
  46. public new FitMode horizontalFit
  47. {
  48. get { return base.horizontalFit; }
  49. set
  50. {
  51. Config.Set(value, (o) => base.horizontalFit = value, (o) => CurrentSettings.HorizontalFit = value);
  52. }
  53. }
  54. public new FitMode verticalFit
  55. {
  56. get { return base.verticalFit; }
  57. set
  58. {
  59. Config.Set(value, (o) => base.verticalFit = value, (o) => CurrentSettings.VerticalFit = value);
  60. }
  61. }
  62. [SerializeField]
  63. RectTransform source;
  64. [SerializeField]
  65. Settings settingsFallback = new Settings();
  66. [SerializeField]
  67. SettingsConfigCollection customSettings = new SettingsConfigCollection();
  68. [SerializeField]
  69. FloatSizeModifier minWidthSizerFallback = new FloatSizeModifier(0, 0, 4000);
  70. [SerializeField]
  71. FloatSizeConfigCollection minWidthSizers = new FloatSizeConfigCollection();
  72. [SerializeField]
  73. FloatSizeModifier minHeightSizerFallback = new FloatSizeModifier(0, 0, 4000);
  74. [SerializeField]
  75. FloatSizeConfigCollection minHeightSizers = new FloatSizeConfigCollection();
  76. [SerializeField]
  77. FloatSizeModifier maxWidthSizerFallback = new FloatSizeModifier(1000, 0, 4000);
  78. [SerializeField]
  79. FloatSizeConfigCollection maxWidthSizers = new FloatSizeConfigCollection();
  80. [SerializeField]
  81. FloatSizeModifier maxHeightSizerFallback = new FloatSizeModifier(1000, 0, 4000);
  82. [SerializeField]
  83. FloatSizeConfigCollection maxHeightSizers = new FloatSizeConfigCollection();
  84. [SerializeField]
  85. Vector2SizeModifier paddingFallback = new Vector2SizeModifier(new Vector2(), new Vector2(-5000, -5000), new Vector2(5000, 5000));
  86. [SerializeField]
  87. Vector2SizeConfigCollection paddingSizers = new Vector2SizeConfigCollection();
  88. [SerializeField]
  89. bool treatAsLayoutElement = true;
  90. RectTransformData start = new RectTransformData();
  91. RectTransformData end = new RectTransformData();
  92. bool isAnimating;
  93. Vector2 lastCalculatedSize;
  94. protected override void OnEnable()
  95. {
  96. base.OnEnable();
  97. Apply();
  98. }
  99. protected override void OnDisable()
  100. {
  101. base.OnDisable();
  102. isAnimating = false;
  103. }
  104. public void OnResolutionChanged()
  105. {
  106. Apply();
  107. }
  108. void Apply()
  109. {
  110. Settings settings = CurrentSettings;
  111. base.m_HorizontalFit = settings.HorizontalFit;
  112. base.m_VerticalFit = settings.VerticalFit;
  113. SetDirty();
  114. }
  115. public override void SetLayoutHorizontal()
  116. {
  117. SetLayout(0);
  118. }
  119. public override void SetLayoutVertical()
  120. {
  121. SetLayout(1);
  122. }
  123. void SetLayout(int axis)
  124. {
  125. if (axis == 0 && CurrentSettings.HorizontalFit == FitMode.Unconstrained)
  126. return;
  127. if (axis == 1 && CurrentSettings.VerticalFit == FitMode.Unconstrained)
  128. return;
  129. if (isAnimating)
  130. return;
  131. if (CurrentSettings.IsAnimated)
  132. {
  133. start.PullFromTransform(this.transform as RectTransform);
  134. }
  135. // disable layout element functionality to prevent wrong size calculation for itself.
  136. bool wasLayoutElement = this.treatAsLayoutElement;
  137. this.treatAsLayoutElement = false;
  138. if (axis == 0)
  139. {
  140. base.SetLayoutHorizontal();
  141. }
  142. else
  143. {
  144. base.SetLayoutVertical();
  145. }
  146. ApplyOffsetToDefaultSize(axis, (axis == 0) ? m_HorizontalFit : m_VerticalFit);
  147. if (CurrentSettings.IsAnimated)
  148. {
  149. end.PullFromTransform(this.transform as RectTransform);
  150. start.PushToTransform(this.transform as RectTransform);
  151. Animate();
  152. }
  153. // restore layout element functionality to prevent wrong size calculation for parent layout groups.
  154. this.treatAsLayoutElement = wasLayoutElement;
  155. }
  156. void ApplyOffsetToDefaultSize(int axis, FitMode fitMode)
  157. {
  158. Vector2 padding = paddingSizers.GetCurrentItem(paddingFallback).CalculateSize(this);
  159. bool hasMax = (axis == 0) ? CurrentSettings.HasMaxWidth : CurrentSettings.HasMaxHeight;
  160. bool hasMin = (axis == 0) ? CurrentSettings.HasMinWidth : CurrentSettings.HasMinHeight;
  161. if (hasMax || hasMin || !Mathf.Approximately(padding[axis], 0) || source != null)
  162. {
  163. float size = (fitMode == FitMode.MinSize)
  164. ? LayoutUtility.GetMinSize(Source, axis)
  165. : LayoutUtility.GetPreferredSize(Source, axis);
  166. size += padding[axis];
  167. size = ClampSize((RectTransform.Axis)axis, size);
  168. lastCalculatedSize[axis] = size;
  169. rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)axis, size);
  170. }
  171. }
  172. float ClampSize(RectTransform.Axis axis, float size)
  173. {
  174. switch (axis)
  175. {
  176. case RectTransform.Axis.Horizontal:
  177. if (CurrentSettings.HasMinWidth)
  178. {
  179. size = Mathf.Max(size, minWidthSizers.GetCurrentItem(minWidthSizerFallback).CalculateSize(this));
  180. }
  181. if (CurrentSettings.HasMaxWidth)
  182. {
  183. size = Mathf.Min(size, maxWidthSizers.GetCurrentItem(maxWidthSizerFallback).CalculateSize(this));
  184. }
  185. break;
  186. case RectTransform.Axis.Vertical:
  187. if (CurrentSettings.HasMinHeight)
  188. {
  189. size = Mathf.Max(size, minHeightSizers.GetCurrentItem(minHeightSizerFallback).CalculateSize(this));
  190. }
  191. if (CurrentSettings.HasMaxHeight)
  192. {
  193. size = Mathf.Min(size, maxHeightSizers.GetCurrentItem(maxHeightSizerFallback).CalculateSize(this));
  194. }
  195. break;
  196. }
  197. return size;
  198. }
  199. Bounds GetChildBounds()
  200. {
  201. RectTransform rt = this.transform as RectTransform;
  202. Bounds bounds = new Bounds();
  203. for (int i = 0; i < transform.childCount; i++)
  204. {
  205. Transform child = transform.GetChild(i);
  206. if (!(child.gameObject.activeSelf))
  207. continue;
  208. Bounds b = RectTransformUtility.CalculateRelativeRectTransformBounds(rt, child);
  209. bounds.Encapsulate(b);
  210. }
  211. return bounds;
  212. }
  213. private void Animate()
  214. {
  215. if (!CurrentSettings.IsAnimated)
  216. return;
  217. this.StopAllCoroutines();
  218. StartCoroutine(CoAnimate());
  219. }
  220. private IEnumerator CoAnimate()
  221. {
  222. float t = 0;
  223. isAnimating = true;
  224. yield return null;
  225. while (t < CurrentSettings.AnimationTime)
  226. {
  227. t += Time.unscaledDeltaTime;
  228. float amount = Mathf.SmoothStep(0, 1, t / CurrentSettings.AnimationTime);
  229. RectTransformData data = RectTransformData.Lerp(start, end, amount);
  230. data.PushToTransform(this.transform as RectTransform);
  231. yield return null;
  232. }
  233. end.PushToTransform(this.transform as RectTransform);
  234. isAnimating = false;
  235. // In case that we missed something during animation
  236. // simply apply the changes without animation
  237. CurrentSettings.IsAnimated = false;
  238. SetLayoutHorizontal();
  239. SetLayoutVertical();
  240. CurrentSettings.IsAnimated = true;
  241. }
  242. #region ILayoutChildDependency
  243. public void ChildSizeChanged(Transform child)
  244. {
  245. ChildChanged();
  246. }
  247. public void ChildAddedOrEnabled(Transform child)
  248. {
  249. ChildChanged();
  250. }
  251. public void ChildRemovedOrDisabled(Transform child)
  252. {
  253. ChildChanged();
  254. }
  255. void ChildChanged()
  256. {
  257. bool tmp = CurrentSettings.IsAnimated;
  258. CurrentSettings.IsAnimated = false;
  259. SetLayoutHorizontal();
  260. SetLayoutVertical();
  261. CurrentSettings.IsAnimated = tmp;
  262. }
  263. #endregion
  264. #region ILayoutElement & ILayoutIgnorer
  265. float ILayoutElement.minWidth
  266. {
  267. get { return treatAsLayoutElement && CurrentSettings.HasMinWidth ? CurrentMinWidth.LastCalculatedSize : -1; }
  268. }
  269. float ILayoutElement.minHeight
  270. {
  271. get { return treatAsLayoutElement && CurrentSettings.HasMinHeight ? CurrentMinHeight.LastCalculatedSize : -1; }
  272. }
  273. float ILayoutElement.preferredWidth
  274. {
  275. get
  276. {
  277. if (!treatAsLayoutElement)
  278. return -1;
  279. SetLayoutHorizontal();
  280. return lastCalculatedSize.x;
  281. }
  282. }
  283. float ILayoutElement.preferredHeight
  284. {
  285. get
  286. {
  287. if (!treatAsLayoutElement)
  288. return -1;
  289. SetLayoutVertical();
  290. return lastCalculatedSize.y;
  291. }
  292. }
  293. float ILayoutElement.flexibleWidth { get { return -1; } }
  294. float ILayoutElement.flexibleHeight { get { return -1; } }
  295. int ILayoutElement.layoutPriority { get { return 1; } }
  296. bool ILayoutIgnorer.ignoreLayout { get { return !treatAsLayoutElement; } }
  297. void ILayoutElement.CalculateLayoutInputHorizontal()
  298. {
  299. SetLayoutHorizontal();
  300. }
  301. void ILayoutElement.CalculateLayoutInputVertical()
  302. {
  303. SetLayoutVertical();
  304. }
  305. #endregion
  306. #if UNITY_EDITOR
  307. protected override void OnValidate()
  308. {
  309. base.OnValidate();
  310. Apply();
  311. }
  312. #endif
  313. }
  314. }