MaintainAspectRatio.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. [RequireComponent(typeof(RawImage))]
  4. public class MaintainAspectRatio : MonoBehaviour
  5. {
  6. //None: 不调整图片大小,使用原始大小。
  7. //FitInParent: 按比例缩放图片以适应固定尺寸的框。
  8. //EnvelopeParent: 按比例缩放图片以覆盖固定尺寸的框。
  9. public enum AspectMode
  10. {
  11. None,
  12. FitInParent,
  13. EnvelopeParent
  14. }
  15. public AspectMode aspectMode = AspectMode.None;
  16. private RawImage rawImage;
  17. private RectTransform parentRectTransform;
  18. void Start()
  19. {
  20. rawImage = GetComponent<RawImage>();
  21. parentRectTransform = transform.parent.GetComponent<RectTransform>();
  22. //AdjustSize();
  23. }
  24. void Update()
  25. {
  26. // 在每帧更新时检查并调整大小
  27. //AdjustSize();
  28. }
  29. public void AdjustSize()
  30. {
  31. if (parentRectTransform == null) return;
  32. if (rawImage.texture == null) return;
  33. Vector2 fixedSize = parentRectTransform.rect.size;
  34. float imageAspect = (float)rawImage.texture.width / rawImage.texture.height;
  35. float targetAspect = fixedSize.x / fixedSize.y;
  36. RectTransform rt = rawImage.GetComponent<RectTransform>();
  37. switch (aspectMode)
  38. {
  39. case AspectMode.FitInParent:
  40. if (imageAspect > targetAspect)
  41. {
  42. // 图片更宽
  43. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.x);
  44. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.x / imageAspect);
  45. }
  46. else
  47. {
  48. // 图片更高
  49. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.y);
  50. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.y * imageAspect);
  51. }
  52. break;
  53. case AspectMode.EnvelopeParent:
  54. if (imageAspect > targetAspect)
  55. {
  56. // 图片更宽
  57. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.y);
  58. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.y * imageAspect);
  59. }
  60. else
  61. {
  62. // 图片更高
  63. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.x);
  64. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.x / imageAspect);
  65. }
  66. break;
  67. case AspectMode.None:
  68. default:
  69. // 原始图片大小
  70. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, rawImage.texture.width);
  71. rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, rawImage.texture.height);
  72. break;
  73. }
  74. }
  75. }