劉海屏適配
項(xiàng)目上線了總免不了適配問題,
注:該方案支持熱更適配,哪怕是上線項(xiàng)目也可以及時開啟適配及調(diào)整適配程度。
原理:
通過獲取設(shè)備型號及計(jì)算屏幕分辨率,在根據(jù)是否劉海屏調(diào)整側(cè)邊按鈕的 Anchored Position 偏移量,從而避過劉海遮擋。文章來源:http://www.zghlxwxcb.cn/news/detail-532092.html
```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
#if UNITY_EDITOR
using Sirenix.Utilities.Editor;
using UnityEditor;
#endif
using UnityEngine;
[ExecuteAlways]
public class UI_NotchAdapter : MonoBehaviour
{
public enum AdapterType
{
ePosY_Minus_AdaptY,
eOffsetMaxY_Minus_AdaptY,
eSizeDeltaY_Set_AdaptY,
eSizeDeltaY_Minus_AdaptY,
}
[System.Serializable]
public class UI_NA_Data
{
[LabelText("需要適配的UI對象")]
public RectTransform mRectTransform_;
[LabelText("適配方式")]
public AdapterType mAdapterType_;
}
[ListDrawerSettings(ShowIndexLabels = true, Expanded = true), LabelText("屏幕適配數(shù)據(jù)"), ShowInInspector]
public List<UI_NA_Data> mAdaptDatas_ = new List<UI_NA_Data>();
private void Awake()
{
}
private void OnDestroy()
{
}
void DoAdapterLogic(bool preview = false)
{
if (mAdaptDatas_ != null)
{
for (var i = 0; i < mAdaptDatas_.Count; ++i)
{
var data = mAdaptDatas_[i];
if (data != null)
{
GameManager gm = null;
if (!preview)
gm = GameManager.Instance;
switch (data.mAdapterType_)
{
case AdapterType.ePosY_Minus_AdaptY:
{
if (data.mRectTransform_ != null)
{
var mPos = data.mRectTransform_.transform.localPosition;
data.mRectTransform_.transform.localPosition = new Vector3(mPos.x, mPos.y - gm.MNotchAdaptY_, mPos.z);
}
}
break;
case AdapterType.eSizeDeltaY_Minus_AdaptY:
{
if (data.mRectTransform_ != null)
{
var rSize = data.mRectTransform_.sizeDelta;
data.mRectTransform_.sizeDelta = new Vector2(rSize.x, rSize.y - gm.MNotchAdaptY_);
}
}
break;
case AdapterType.eSizeDeltaY_Set_AdaptY:
{
if (data.mRectTransform_ != null)
{
var rSize = data.mRectTransform_.sizeDelta;
data.mRectTransform_.sizeDelta = new Vector2(rSize.x, gm.MNotchAdaptY_);
}
}
break;
case AdapterType.eOffsetMaxY_Minus_AdaptY:
{
if (data.mRectTransform_ != null)
{
var rectTop = data.mRectTransform_.offsetMax.y;
var rectRight = data.mRectTransform_.offsetMax.x;
data.mRectTransform_.offsetMax = new Vector2(rectRight, rectTop - gm.MNotchAdaptY_);
}
}
break;
}
}
}
}
}
// Start is called before the first frame update
void Start()
{
if (Application.isPlaying)
{
DoAdapterLogic();
}
}
}
將該代碼掛到需要調(diào)整的適配的ui上,需要注意的是gm.MNotchAdaptY_是劉海屏的高度,需要自己設(shè)置更換。
使用如下:
拖動對應(yīng)的對象,選好適配方式即可文章來源地址http://www.zghlxwxcb.cn/news/detail-532092.html
到了這里,關(guān)于【Unity】工具類系列——UI劉海屏適配的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!