Unity3d UGUI基于屏幕尺寸的自适应

现有的自适应方法,通常都是基于屏幕的分辨率。分辨率越高的设备上,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的错乱。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容