Unity之分辨率适配

一、分辨率适配思考

一套标准的分辨率,如:1920*1080,在发布后快速适配不同机器的分辨率,省事省钱。
程序目标:通过对Resulotion的动态配置,达到发布后所有UI物体自动适配当前设置的Resulotion的目的。

二、核心代码

1.对CanvasScaler进行设置

                    canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
                    canvasScaler.referenceResolution = realResulotion;
                    canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand;
                    canvasScaler.matchWidthOrHeight = 0.5f;

2.对UI物体进行设置

                    Vector2 size = rectTransform.sizeDelta;
                    Vector3 pos = rectTransform.localPosition;

                    if(realResulotion != standardResulotion) {
                        float widthPrecent = realResulotion.x / standardResulotion.x;
                        float heightPrecent = realResulotion.y / standardResulotion.y;
                        rectTransform.sizeDelta = new Vector2(size.x * widthPrecent, size.y * heightPrecent);
                        pos = new Vector3(pos.x * widthPrecent, pos.y * heightPrecent, 0);
                    }

                    rectTransform.localPosition = pos;

三、扩展方向

1.自动关联不同机器下对应的不同分辨率图片挂载到UI物体;
2.当前采用的思路是保持一个分辨率的比例,尽量使UI物体的间隔距离一致和整体布局与预设分辨率情况一致,但是会在较大差异分辨率之间导致UI物体的形变比较严重;
3.打包成dll或插件,在导入Unity时自动创建MutiResulotionMatcher/Config.xml到指定目录。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章