天天看點

UnityEngine.Screen.safeArea

Unity 2017.2.1及以後

Screen.safeArea會傳回移動平台安全區的Rect。

參考代碼:

public class SafeArea : MonoBehaviour
{
    float safeArea_left;
    // Start is called before the first frame update
    void Start()
    {
        safeArea_left = UnityEngine.Screen.safeArea.left;
    }

    // Update is called once per frame
    void Update()
    {
        if (Screen.orientation ==UnityEngine.ScreenOrientation.LandscapeLeft)
        {
            
            gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(safeArea_left, gameObject.GetComponent<RectTransform>().anchoredPosition.y);
        }
        else
        {
            gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, gameObject.GetComponent<RectTransform>().anchoredPosition.y);
        }
    }
}
           

上述代碼是為了實作如下效果:

當使用者向左橫握手機,螢幕左側圖檔吸附在劉海處;當使用者向右橫握手機,螢幕左側圖檔吸附在手機底部。

借鑒連結:

https://zhuanlan.zhihu.com/p/124246847