用UGUI做東西的時候,自適應選擇scalewithscreensize,默認是基於高度進行等比縮放,參見上一篇NGUI自適應,但是UGUI有個叫做Anchor的東西,即當前圖片相對於父節點的位置,將anchor的四個角與自己的四個角關聯在一起,既可以實現非等比縮放。即物體的大小就等於四個anchor所形成的區域,一般是屏幕的百分比。如果要使屏幕在寬高比低於某個標准值的時候表現為頂部和底部出現黑邊,大於標准值橫向拉伸,可以在Canvas下面添加一個panel,動態的去改變該panel的大小即可。
private readonly float _refWidth = 960.0f; private readonly float _refHeight = 640.0f; private readonly float _refRatio = 960.0f / 640.0f; // Use this for initialization void Start () { if (Screen.width * 1.0f / Screen.height > _refRatio) { GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width / (Screen.height / _refHeight), _refHeight); } else { GetComponent<RectTransform>().sizeDelta = new Vector2(_refWidth, _refHeight); } }
