ResponsiveResize.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. namespace SRF.UI
  2. {
  3. using System;
  4. using Internal;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. [ExecuteInEditMode]
  8. [RequireComponent(typeof (RectTransform))]
  9. [AddComponentMenu(ComponentMenuPaths.ResponsiveResize)]
  10. public class ResponsiveResize : ResponsiveBase
  11. {
  12. public Element[] Elements = new Element[0];
  13. protected override void Refresh()
  14. {
  15. var rect = RectTransform.rect;
  16. for (var i = 0; i < Elements.Length; i++)
  17. {
  18. var e = Elements[i];
  19. if (e.Target == null)
  20. {
  21. continue;
  22. }
  23. var maxWidth = float.MinValue;
  24. var selectedWidth = -1f;
  25. for (var j = 0; j < e.SizeDefinitions.Length; j++)
  26. {
  27. var d = e.SizeDefinitions[j];
  28. // If the threshold applies
  29. if (d.ThresholdWidth <= rect.width)
  30. {
  31. // And it is the largest width so far
  32. if (d.ThresholdWidth > maxWidth)
  33. {
  34. // Set it as active
  35. maxWidth = d.ThresholdWidth;
  36. selectedWidth = d.ElementWidth;
  37. }
  38. }
  39. }
  40. if (selectedWidth > 0)
  41. {
  42. e.Target.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, selectedWidth);
  43. var le = e.Target.GetComponent<LayoutElement>();
  44. if (le != null)
  45. {
  46. le.preferredWidth = selectedWidth;
  47. }
  48. }
  49. }
  50. }
  51. [Serializable]
  52. public struct Element
  53. {
  54. public SizeDefinition[] SizeDefinitions;
  55. public RectTransform Target;
  56. [Serializable]
  57. public struct SizeDefinition
  58. {
  59. [Tooltip("Width to apply when over the threshold width")] public float ElementWidth;
  60. [Tooltip("Threshold over which this width will take effect")] public float ThresholdWidth;
  61. }
  62. }
  63. }
  64. }