Unity UI 的元件,若是要自動因應不同尺寸螢幕與解析度做縮放,除了需要縮放物件尺寸外,也得修正物件錨點相對位置,才不會讓縮放後的物件亂跑喔!
以下是實際範例:
(1) 螢幕尺寸變更前,原螢幕參考尺寸 X 1080、Y 1920
(2) 螢幕尺寸變更之UI物件尺寸縮放,變更後螢幕參考尺寸 X 1080、Y 2400
(3) 螢幕尺寸變更之UI物件錨點相對位置偏移修正
(4) 計算螢幕尺寸變更後的UI縮放比例程式 CavasScaleCalc.cs:本例中,要將此程式拉進 Canvas 元件中.
// CanvasScaleCalc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CanvasScaleCalc : MonoBehaviour
{
//private Camera _MainCamera;
public float screenWidthScale;
public float screenHeightScale;
public float _referenceResolutionX;
public float _referenceResolutionY;
public float _ScreenWidth;
public float _ScreenHeight;
private CanvasScaler _canvasScaler;
private void Awake() {
// 計算 Screen 與參考 Screen 調整比率
_canvasScaler = GetComponent<CanvasScaler>();
_ScreenWidth = Screen.width;
_ScreenHeight = Screen.height;
_referenceResolutionX = _canvasScaler.referenceResolution.x;
_referenceResolutionY = _canvasScaler.referenceResolution.y;
screenWidthScale = _ScreenWidth / _referenceResolutionX;
screenHeightScale = _ScreenHeight / _referenceResolutionY;
}
}
(5) 設定螢幕尺寸變更後UI物件縮放與錨點偏移修正程式:本例中,是將此程式放進 UI 物件 MutiSceneText 元件中.
// MutiSceneText.cs
(6) 試試!^_^
沒有留言:
張貼留言