52 lines
2.3 KiB
C#
52 lines
2.3 KiB
C#
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);
|
||
}
|
||
}
|
||
}
|
||
} |