刘海屏适配
项目上线了总免不了适配问题,
注:该方案支持热更适配,哪怕是上线项目也可以及时开启适配及调整适配程度。
原理:
通过获取设备型号及计算屏幕分辨率,在根据是否刘海屏调整侧边按钮的 Anchored Position 偏移量,从而避过刘海遮挡。文章来源:https://www.toymoban.com/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("屏幕适配数据"), 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();
}
}
}
将该代码挂到需要调整的适配的ui上,需要注意的是gm.MNotchAdaptY_是刘海屏的高度,需要自己设置更换。
使用如下:
拖动对应的对象,选好适配方式即可文章来源地址https://www.toymoban.com/news/detail-532092.html
到了这里,关于【Unity】工具类系列——UI刘海屏适配的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!