現(xiàn)有的自適應(yīng)方法索赏,通常都是基于屏幕的分辨率猜憎。分辨率越高的設(shè)備上朴皆,UI顯示的越小帕识。這就造成了一些5寸左右的手機(jī)分辨率比ipad等平板設(shè)備還要高。UI在平板上顯示太大遂铡。但是在高分辨率手機(jī)上顯示太小肮疗。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class ScreenAdaptive : MonoBehaviour
{
public List<CanvasScaler> UICanvas;
private float diagonalInches;
private float width;
private float height;
private float ypotinousa;
private float dpi;
private float screenScale;
void screenInch()
{
dpi = Screen.dpi;
if (dpi < 25 || dpi > 1000)
{
dpi = 150;
}
width = Screen.width * Screen.width;
height = Screen.height * Screen.height;
ypotinousa = width + height;
ypotinousa = Mathf.Sqrt(ypotinousa);
diagonalInches = ypotinousa / Screen.dpi;
}
void Awake()
{
if (Application.isMobilePlatform)
{
screenInch();
//以五寸屏幕作為標(biāo)準(zhǔn)
screenScale = diagonalInches / 5f;
for (int i = 0; i < UICanvas.Count; i++)
{
Vector2 _size = UICanvas[i].referenceResolution;
UICanvas[i].referenceResolution = _size * screenScale;
if (UICanvas[i].GetComponent<Canvas>().renderMode == RenderMode.ScreenSpaceCamera)
{
UICanvas[i].GetComponent<Canvas>().worldCamera.orthographicSize *= screenScale;
}
}
}
}
}
以上腳本為基于屏幕物理尺寸自適應(yīng)UI的一種方法。通過計(jì)算屏幕的DPI獲取到屏幕的實(shí)際尺寸扒接。然后根據(jù)一個(gè)標(biāo)準(zhǔn)的尺寸對UI的分辨率進(jìn)行相對應(yīng)的縮放伪货。
可以改進(jìn)的地方就是對于大屏幕或者小屏幕進(jìn)行縮放的限制。避免類似ipad pro這類的設(shè)備上钾怔,UI有小的離譜碱呼。
配合這個(gè)腳本使用的同時(shí)。UI也需要用到錨點(diǎn)宗侦,進(jìn)行初步的自適應(yīng)愚臀,不然會造成UI的錯(cuò)亂。