现有的自适应方法,通常都是基于屏幕的分辨率。分辨率越高的设备上,UI显示的越小。这就造成了一些5寸左右的手机分辨率比ipad等平板设备还要高。UI在平板上显示太大。但是在高分辨率手机上显示太小。
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();
//以五寸屏幕作为标准
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;
}
}
}
}
}
以上脚本为基于屏幕物理尺寸自适应UI的一种方法。通过计算屏幕的DPI获取到屏幕的实际尺寸。然后根据一个标准的尺寸对UI的分辨率进行相对应的缩放。
可以改进的地方就是对于大屏幕或者小屏幕进行缩放的限制。避免类似ipad pro这类的设备上,UI有小的离谱。
配合这个脚本使用的同时。UI也需要用到锚点,进行初步的自适应,不然会造成UI的错乱。
网友评论