Unity3D UI适配问题:小米设备画面超出相机黑边范围
小米设备相机黑边适配异常问题排查与修复
问题描述
在适配游戏画面比例时,遇到了小米设备上画面绘制到相机黑边(letterbox)之外的问题,其他品牌设备(如三星)显示均正常。已对比两款设备的截图:小米设备显示效果异常,三星设备显示效果符合预期。当前使用的适配代码如下:
float targetaspect = 750f / 1334f; // 确定游戏窗口当前的宽高比 float windowaspect = (float)Screen.width / (float)Screen.height; // 当前视口高度应按此比例缩放 float scaleheight = windowaspect / targetaspect; // 获取相机组件以修改其视口 Camera camera = GetComponent<Camera>(); // 若缩放高度小于1,则添加黑边 if (scaleheight < 1.0f) { Rect rect = camera.rect; rect.width = 1.0f; rect.height = scaleheight; rect.x = 0; rect.y = (1.0f - scaleheight) / 2.0f; camera.rect = rect; }
问题分析
小米部分设备的屏幕可能存在特殊的显示区域(如刘海、挖孔或系统级的显示偏移),或者Unity在小米设备上对Camera.rect的解析存在差异。你的代码逻辑是基于标准宽高比计算,但没有考虑到设备实际可用显示区域与屏幕分辨率的差异,导致相机视口的设置没有被正确应用,最终画面溢出到黑边外。
解决方案
尝试以下几种修复方案,逐步验证:
- 改用
Camera.pixelRect替代Camera.rectCamera.rect基于屏幕归一化坐标(0-1),而Camera.pixelRect使用实际像素值,在小米设备上可能更精准:
float targetaspect = 750f / 1334f; float windowaspect = (float)Screen.width / (float)Screen.height; float scaleheight = windowaspect / targetaspect; Camera camera = GetComponent<Camera>(); if (scaleheight < 1.0f) { int targetHeight = Mathf.RoundToInt(Screen.width / targetaspect); int yOffset = (Screen.height - targetHeight) / 2; camera.pixelRect = new Rect(0, yOffset, Screen.width, targetHeight); } else { // 处理宽屏情况(可选) float scalewidth = 1.0f / scaleheight; int targetWidth = Mathf.RoundToInt(Screen.height * targetaspect); int xOffset = (Screen.width - targetWidth) / 2; camera.pixelRect = new Rect(xOffset, 0, targetWidth, Screen.height); }
- 结合安全区域调整视口
部分小米设备系统会预留安全区域(如刘海下方),可以结合Screen.safeArea来修正相机视口:
Rect safeArea = Screen.safeArea; float targetaspect = 750f / 1334f; float windowaspect = safeArea.width / safeArea.height; float scaleheight = windowaspect / targetaspect; Camera camera = GetComponent<Camera>(); if (scaleheight < 1.0f) { float normalizedHeight = scaleheight; float normalizedY = (1.0f - normalizedHeight) / 2.0f; // 叠加安全区域的Y轴偏移量 normalizedY += (safeArea.y / Screen.height); camera.rect = new Rect(0, normalizedY, 1, normalizedHeight); }
- 使用Unity默认适配方案
在Player Settings中设置Aspect Ratio为Fixed Height或Fixed Width,选择目标比例750x1334,让Unity自动处理黑边适配,避免手动修改相机视口带来的兼容问题。
验证建议
- 在小米设备上测试修改后的代码,对比截图确认画面是否被限制在黑边内;
- 同时测试其他品牌设备,确保原有正常显示的设备不受影响。
内容的提问来源于stack exchange,提问作者Данияр
相关产品推荐
相关产品推荐

