Unity 微信小游戏 UI 屏幕适配
这是微信小游戏官方的适配文档地址:
https://github.com/wechat-miniprogram/minigame-unity-webgl-transform/blob/98aed655cc536f1e1dc21524516c40c442594ac1/Design/fixScreen.md
里面的示例代码并不好用,这里给出项目中调试好的代码:
#if WEIXINMINIGAME
private void SetWXSafeArea()
{
var info = WeChatWASM.WX.GetSystemInfoSync();
//顶部区域安全差异比例
float py = (float) info.safeArea.top / (float) info.windowHeight;
//底部区域安全差异比例
float by = ((float) info.windowHeight -(float) info.safeArea.bottom) / (float) info.windowHeight;
//得到当前canvasScaler
var cs = canvas.GetComponent<CanvasScaler>();
//调整offsetMax.y - 顶部偏移 和offsetMin.y - 底部偏移。
//m_SafeAreaContainer是当前界面的顶部RectTransfrom。
//注意:这里的m_SafeAreaContainer原本是完全填充屏幕的。
m_SafeAreaContainer.offsetMax = new Vector2(m_SafeAreaContainer.offsetMax.x, m_SafeAreaContainer.offsetMax.y -(cs.referenceResolution.y * py) );
m_SafeAreaContainer.offsetMin = new Vector2(m_SafeAreaContainer.offsetMin.x, (m_SafeAreaContainer.offsetMin.y + cs.referenceResolution.y * (by)));
// 重新计算缩放,让高度占满刘海屏以下的区域
cs.referenceResolution = new Vector2(cs.referenceResolution.x , cs.referenceResolution.y * (1 - (py + by)));
}
#endif
这样适配就完成了。