天天看點

Unity開發中劉海屏手機的螢幕适配

Unity UGUI在劉海屏手機的螢幕适配主要是針對iPhoneX的适配。

解決方法是每一個界面的最上層都是一個橫縱Stretch自動拉伸的,當檢測到目前是IPhoneX時,打開界面代碼自動設定Left Top Right Bottom 為44.

通過分辨率來判斷目前手機是不是iPhoneX。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

/// <summary>

/// 自适應iPhoneX

/// </summary>

/// <param name="canvas">Canvas.</param>

private void OpeniPhoneX(Canvas canvas){

#if UNITY_IPHONE

if (Screen.width == 2436 && Screen.height == 1125){

RectTransform rectTransform = (canvas.transform as RectTransform);

rectTransform.offsetMin = new Vector2(44f,0f);

rectTransform.offsetMax = new Vector2(-44f,0f);

}

#endif

}

接着就是界面最下面可能有些需要全屏的圖,這樣就不全屏了,是以需要給全屏圖挂一個腳本。一般做全屏圖有兩種方式,一個是自動拉伸的,另一個就是AspectTatioFitter帶裁切的全屏。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

/// <summary>

/// 自适應iPhoneX背景

/// </summary>

public class UIRectLayout : MonoBehaviour

{

#if UNITY_IPHONE

void Awake () {

if (Screen.width == 2436 && Screen.height == 1125) {

AspectRatioFitter aspectRatioFitter = GetComponent<AspectRatioFitter> ();

if (aspectRatioFitter) {

aspectRatioFitter.aspectRatio = 2.165333f;

} else {

RectTransform rectTransform = transform as RectTransform;

if (rectTransform.anchorMax.x == 1f) {

rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x - 44f,rectTransform.offsetMin.y);

rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x +44f,rectTransform.offsetMax.y);

}

}

}

}

#endif

}