using UnityEngine;
using UnityEngine.UI;
public class Image_Mono_ : MonoBehaviour
{
[SerializeField] private RectTransform panel;// panel
[SerializeField] private Image img;// image
[ContextMenu("SetImage")]
private void SetImage()
{
// 判空
if (panel == null || img == null)
return;
// 设置最初比例
img.SetNativeSize();
// 获取当前图片的宽度和高度
float imgWidth = img.rectTransform.rect.x;
float imgHeight = img.rectTransform.rect.y;
// 获取Panel的宽度和高度
float panelWidth = panel.rect.width;
float panelHeight = panel.rect.height;
// 计算缩放比例
float scaleFactor = 1f;
// 当图片的宽度大于高度时,设置图片的高度
// 当图片的宽度大于高度是,将图片的宽度设置为Panel的宽度,否则反之
if (imgWidth > imgHeight)
{
scaleFactor = panelWidth / imgWidth;
}
else
{
scaleFactor = panelHeight / imgHeight;
}
img.rectTransform.sizeDelta = new Vector2(imgWidth * scaleFactor, imgHeight * scaleFactor);
}
}
05-23
837

08-05
08-05