ar_tourism_flutter_unity/unity/VRProject2/Assets/zhl/zhlScripts/RawImageAspectFitter.cs
2025-05-14 17:04:13 +08:00

52 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(RawImage))]
public class RawImageAspectFitter : MonoBehaviour {
public enum FitMode { Contain, Cover }
public FitMode fitMode = FitMode.Contain; // 选择模式
private RawImage rawImage;
private RectTransform rectTransform;
void Start() {
rawImage = GetComponent<RawImage>();
rectTransform = GetComponent<RectTransform>();
UpdateAspect();
}
void UpdateAspect() {
if (rawImage.texture == null) return;
// 获取容器和图片的宽高比例
float containerWidth = rectTransform.rect.width;
float containerHeight = rectTransform.rect.height;
float containerRatio = containerWidth / containerHeight;
float textureRatio = (float)rawImage.texture.width / rawImage.texture.height;
// 计算缩放比例
float scaleWidth, scaleHeight;
if (fitMode == FitMode.Contain) {
// Contain模式按比例缩放完整显示图片
if (textureRatio > containerRatio) {
scaleHeight = containerWidth / textureRatio;
scaleWidth = containerWidth;
} else {
scaleWidth = containerHeight * textureRatio;
scaleHeight = containerHeight;
}
// 居中显示,留白
rawImage.uvRect = new Rect(0, 0, 1, 1);
rectTransform.sizeDelta = new Vector2(scaleWidth, scaleHeight);
} else {
// Cover模式按比例缩放裁剪图片填满容器
if (textureRatio > containerRatio) {
// 横向裁剪
float scale = containerHeight / rawImage.texture.height;
float visibleWidth = rawImage.texture.width * scale;
float offsetX = (visibleWidth - containerWidth) / (2 * visibleWidth);
rawImage.uvRect = new Rect(offsetX, 0, containerWidth / visibleWidth, 1);
} else {
// 纵向裁剪
float scale = containerWidth / rawImage.texture.width;
float visibleHeight = rawImage.texture.height * scale;
float offsetY = (visibleHeight - containerHeight) / (2 * visibleHeight);
rawImage.uvRect = new Rect(0, offsetY, 1, containerHeight / visibleHeight);
}
}
}
}