using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(RawImage))] public class MaintainAspectRatio : MonoBehaviour { //None: 不调整图片大小,使用原始大小。 //FitInParent: 按比例缩放图片以适应固定尺寸的框。 //EnvelopeParent: 按比例缩放图片以覆盖固定尺寸的框。 public enum AspectMode { None, FitInParent, EnvelopeParent } public AspectMode aspectMode = AspectMode.None; private RawImage rawImage; private RectTransform parentRectTransform; void Start() { rawImage = GetComponent(); parentRectTransform = transform.parent.GetComponent(); //AdjustSize(); } void Update() { // 在每帧更新时检查并调整大小 //AdjustSize(); } public void AdjustSize() { if (parentRectTransform == null) return; if (rawImage.texture == null) return; Vector2 fixedSize = parentRectTransform.rect.size; float imageAspect = (float)rawImage.texture.width / rawImage.texture.height; float targetAspect = fixedSize.x / fixedSize.y; RectTransform rt = rawImage.GetComponent(); switch (aspectMode) { case AspectMode.FitInParent: if (imageAspect > targetAspect) { // 图片更宽 rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.x); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.x / imageAspect); } else { // 图片更高 rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.y); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.y * imageAspect); } break; case AspectMode.EnvelopeParent: if (imageAspect > targetAspect) { // 图片更宽 rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.y); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.y * imageAspect); } else { // 图片更高 rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fixedSize.x); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, fixedSize.x / imageAspect); } break; case AspectMode.None: default: // 原始图片大小 rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, rawImage.texture.width); rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, rawImage.texture.height); break; } } }