public class AdjustCamera : MonoBehaviour {
private new Camera camera;
[SerializeField]
private TargetScreenSize sizeScreenTarget;
// 构造函数
private AdjustCamera() { }
void Awake()
{
camera = GetComponent<Camera>();
}
void Start()
{
AdjustRatio();
}
private void AdjustRatio()
{
float targetAspect = sizeScreenTarget.width / sizeScreenTarget.height;
float screenAspect = (float)Screen.width / (float)Screen.height;
float scaleHeight = screenAspect / targetAspect;
if (scaleHeight < 1.0f)
{
Rect rect = camera.rect;
rect.width = 1.0f;
rect.height = scaleHeight;
rect.x = 0;
rect.y = (1.0f - scaleHeight) / 2.0f;
camera.rect = rect;
}
else
{
float scaleWidth = 1.0f / scaleHeight;
Rect rect = camera.rect;
rect.width = scaleWidth;
rect.height = 1.0f;
rect.x = (1.0f - scaleWidth) / 2.0f;
rect.y = 0;
camera.rect = rect;
}
}
}
[System.Serializable]
public struct TargetScreenSize
{
public float width;
public float height;
}
配合:挂Canvas上
/****************************************************
文件:CanvasCtrl.cs
作者:Edision
邮箱: 424054763@qq.com
日期:#CreateTime#
功能:Nothing
*****************************************************/
using UnityEngine;
using UnityEngine.UI;
public class CanvasCtrl : MonoBehaviour
{
void Start()
{
float standard_width = 1080f; //初始宽度
float standard_height = 1920f; //初始高度
float device_width = 0f; //当前设备宽度
float device_height = 0f; //当前设备高度
float adjustor = 0f; //屏幕矫正比例
//获取设备宽高
device_width = Screen.width;
device_height = Screen.height;
//计算宽高比例
float standard_aspect = standard_width / standard_height;
float device_aspect = device_width / device_height;
//计算矫正比例
if (device_aspect < standard_aspect)
{
adjustor = standard_aspect / device_aspect;
}
CanvasScaler canvasScalerTemp = transform.GetComponent<CanvasScaler>();
if (adjustor == 0)
{
canvasScalerTemp.matchWidthOrHeight = 1;
}
else
{
canvasScalerTemp.matchWidthOrHeight = 0;
}
}
}