【Unity3D】微信小游戏适配安全区域或胶囊控件(圆圈按钮)水平高度一致方案

发布于:2025-07-09 ⋅ 阅读:(13) ⋅ 点赞:(0)

面板保持如下RectTransform数据配置,挂上脚本,然后其子UI都要向上对齐,即

如下脚本是控制将面板的上边界与胶囊控件(圆心设置按钮)上边界水平对齐。

var topSize = rect.top;  这一行代码是获取到胶囊控件上边界,改为其他的就可以与其他位置水平对齐。
例如: var topSize = rect.bottom; 与胶囊控件下边界对齐
例如: var topSize = _sInfo.safeArea.top; 与安全区域上边界对齐(刘海屏下边界)
... ...

using System;
using Newtonsoft.Json;
using UnityEngine;
using WeChatWASM;

public class TopPanelAdapt : MonoBehaviour
{
    //开发阶段自定义posY
    public float posY = 0f;
    
    void Start()
    {
    //微信宏(具体项目可能不同)
#if UNITY_WEBGL || WEIXINMINIGAME || UNITY_EDITOR
        InitTop();
#endif
    }

    void InitTop()
    {
        var top_panel = GetComponent<RectTransform>();
        //胶囊控件区域信息
        var rect = WX.GetMenuButtonBoundingClientRect();
        //屏幕信息
        var _sInfo = WeChatWASM.WX.GetWindowInfo();
        if (rect != null && _sInfo != null)
        {
            var sHeight = _sInfo.windowHeight;
            top_panel.sizeDelta = Vector2.zero;
            
            var topSize = rect.top;
            //开发分辨率: 750 x 1334 (具体项目可能不同)
            //垂直px to rpx操作 从微信获取的是px像素尺寸 需转为Unity的rpx尺寸
            float newSize = (float)topSize * (1334f / UnityEngine.Screen.height);
            //PS: 如果是水平px 则是  px * (750f / UnityEngine.Screen.width);
            topSize = newSize;

            double t = 0;
            if (topSize > 0)
            {
                t = topSize / sHeight;
            }

            top_panel.pivot = new Vector2(0.5f, 0.5f);
            top_panel.anchorMin = new Vector2(0, 0);
            top_panel.anchorMax = new Vector2(1, 1 - (float)t);
        }
        else
        {
            top_panel.offsetMax = new Vector2(top_panel.offsetMax.x, -posY);
        }
    }
}