目的
图像大小是固定,直到屏幕的大小小于这个图像大小时,图像在保持自身长宽不变的情况下,缩小到可以在这个屏幕中完整观看的尺寸。
结果
目前需要跑运行模式,而且要作为该图的组件
对象设置
- 组织:
- background的Canvas设置
- Panel设置为填满
- Image 加入"AutoUiSize"的组件(下面有代码),设置为居中
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoUiSize : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
void UpdateSize(){
RectTransform rt = GetComponent<RectTransform>();
if(rt.rect.width > Screen.width || rt.rect.height > Screen.height){
if(Screen.width / Screen.height < rt.rect.width / rt.rect.height ){
float scale = Screen.width / rt.rect.width;
rt.localScale = new Vector3(scale, scale, scale);
Debug.Log("Scale is " + scale);
}else{
float scale = Screen.height / rt.rect.height;
rt.localScale = new Vector3(scale, scale, scale);
Debug.Log("Scale is " + scale);
}
}
}
// Update is called once per frame
void Update()
{
UpdateSize();
}
}