unity android刘海,unity刘海屏适配

这个博客介绍了一个Unity脚本,用于获取和应用屏幕的安全区域,以确保UI元素在不同设备上正确显示。它涉及到锚点的计算和更新,以及在C#和Lua中如何调用和使用这些功能进行UI布局的调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class SafeArea : MonoBehaviour

{

private Rect _safeArea;

public ActionApplySafeArea;

void Update()

{

if (getSafeArea() != _safeArea)

{

_safeArea = getSafeArea();

applySafeArea();

}

}

private void applySafeArea()

{

Vector2[] anchors = getAnchor();

ApplySafeArea?.Invoke(anchors[0], anchors[1]);

}

private Vector2[] getAnchor()

{

Rect rect = getSafeArea();

Vector2 anchorMin = rect.position;

Vector2 anchorMax = rect.position + rect.size;

anchorMin.x /= Screen.width;

anchorMax.x /= Screen.width;

anchorMin.y /= Screen.height;

anchorMax.y /= Screen.height;

return new Vector2[] { anchorMin, anchorMax};

}

private Rect getSafeArea()

{

Rect rect = Screen.safeArea;

#if UNITY_EDITOR

rect = PLAGame.Client.LuaHelper.GetSafeArea();

#endif

return rect;

}

class Luahelper{

public static void ApplySafeArea(GameObject go, Actionaction)

{//go指的是一个大UI的父对象

SafeArea safeArea = go.CheckAndAddComponent();

safeArea.ApplySafeArea = action;

}

}

function SafeArea.ApplyCustomPanle(go, cb ) go指的是一个大UI的父对象

LuaHelper.ApplySafeArea(go, function (anchorMin, anchorMax )

cb(anchorMin, anchorMax)

end)

end

//C#示例

ApplySafeArea(go,(Vector2 anchorMin , Vector2 anchorMax )=>{

var t1 = go.transform.GetChild(0).RectTransform

t1 .anchorMin = Vector2(anchorMin.x, 1)

t1 .anchorMin = Vector2(anchorMin.x, 1)

})

//lua示例

SafeArea.ApplyCustomPanle(self.view.go, function ( anchorMin, anchorMax )

print(anchorMin)

print(anchorMax)

local tran = self.view.go.transform

tran:GetChild(1).anchorMin = Vector2(anchorMin.x, 1)

tran:GetChild(2).anchorMin = Vector2(anchorMin.x, 0)

tran:GetChild(3).anchorMin = Vector2(anchorMax.x, 1)

tran:GetChild(3).anchorMax = Vector2(anchorMax.x, 1)

tran:GetChild(4).anchorMin = Vector2(anchorMin.x, 0)

tran:GetChild(4).anchorMax = Vector2(anchorMax.x, 1)

end)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值