开发环境
- Unity2021.3.39f1
代码
因为设备的纵横比例与开发环境的纵横比例是不同的,此时需要根据移动设备的纵横比例去调整CanvasScaler的Match参数,可获得最好的UI展示效果。
代码是给竖屏做的适配。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 自适应调整CanvasScale的Match
/// </summary>
[DisallowMultipleComponent]
[RequireComponent(typeof(CanvasScaler))]
public class AutoResolutionScaler : MonoBehaviour
{
[HideInInspector]
public CanvasScaler BindCanvasScaler;
[HideInInspector]
public Vector2 DevelopReferenceResolution;
[HideInInspector]
public float DevelopResolutionRatio = 1;
private void Awake()
{
BindCanvasScaler = GetComponent<CanvasScaler>();
if (null == BindCanvasScaler)
{
Debug.LogError($"{gameObject.name} need CanvasScaler !");
return;
}
if (BindCanvasScaler.uiScaleMode != CanvasScaler.ScaleMode.ScaleWithScreenSize)
{
Debug.LogError($"{gameObject.name} CanvasScaler uiScaleMode is not ScaleWithScreenSize !");
return;
}
if (BindCanvasScaler.screenMatchMode != CanvasScaler.ScreenMatchMode.MatchWidthOrHeight)
{
Debug.LogError($"{gameObject.name} CanvasScaler screenMatchMode is not MatchWidthOrHeight !");
return;
}
//x与y的比例
DevelopReferenceResolution = BindCanvasScaler.referenceResolution;
DevelopResolutionRatio = DevelopReferenceResolution.y / DevelopReferenceResolution.x;
// 1920 / 1080 = 1.778
// 2160 / 1440 = 1.5
// 1280 / 720 = 1.778
// 2340 / 1080 = 2.167
float deviceResolutionRatio = Screen.height / Screen.width;
if (deviceResolutionRatio >= DevelopResolutionRatio)
{
BindCanvasScaler.matchWidthOrHeight = 0;
}
else
{
BindCanvasScaler.matchWidthOrHeight = 1;
}
}
}