UniGifImageAspectController.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. UniGif
  3. Copyright (c) 2015 WestHillApps (Hironari Nishioka)
  4. This software is released under the MIT License.
  5. http://opensource.org/licenses/mit-license.php
  6. */
  7. using UnityEngine;
  8. [ExecuteInEditMode]
  9. public class UniGifImageAspectController : MonoBehaviour
  10. {
  11. public int m_originalWidth;
  12. public int m_originalHeight;
  13. public bool m_fixOnUpdate;
  14. private Vector2 m_lastSize = Vector2.zero;
  15. private Vector2 m_newSize = Vector2.zero;
  16. private RectTransform m_rectTransform;
  17. public RectTransform rectTransform
  18. {
  19. get
  20. {
  21. return m_rectTransform != null ? m_rectTransform : (m_rectTransform = GetComponent<RectTransform>());
  22. }
  23. }
  24. private void Update()
  25. {
  26. #if UNITY_EDITOR
  27. if (Application.isPlaying == false)
  28. {
  29. FixAspectRatio();
  30. return;
  31. }
  32. #endif
  33. if (m_fixOnUpdate)
  34. {
  35. FixAspectRatio();
  36. }
  37. }
  38. public void FixAspectRatio(int originalWidth = -1, int originalHeight = -1)
  39. {
  40. bool forceUpdate = false;
  41. if (originalWidth > 0 && originalHeight > 0)
  42. {
  43. m_originalWidth = originalWidth;
  44. m_originalHeight = originalHeight;
  45. forceUpdate = true;
  46. }
  47. if (m_originalWidth <= 0 || m_originalHeight <= 0)
  48. {
  49. return;
  50. }
  51. bool changeX;
  52. if (forceUpdate || m_lastSize.x != rectTransform.sizeDelta.x)
  53. {
  54. changeX = true;
  55. }
  56. else if (m_lastSize.y != rectTransform.sizeDelta.y)
  57. {
  58. changeX = false;
  59. }
  60. else
  61. {
  62. return;
  63. }
  64. if (changeX)
  65. {
  66. float ratio = rectTransform.sizeDelta.x / m_originalWidth;
  67. m_newSize.Set(rectTransform.sizeDelta.x, m_originalHeight * ratio);
  68. }
  69. else
  70. {
  71. float ratio = rectTransform.sizeDelta.y / m_originalHeight;
  72. m_newSize.Set(m_originalWidth * ratio, rectTransform.sizeDelta.y);
  73. }
  74. rectTransform.sizeDelta = m_newSize;
  75. m_lastSize = rectTransform.sizeDelta;
  76. }
  77. }