终于下了决心开始写博客,想来想去还是先写个最近刚解决的问题。RT
我们项目使用的1280*720,也就是16:9的开发屏幕宽高比。因为开始做屏幕适配的时候有点晚了,然后游戏也不是那种很需要操作的,接着参考了下几个在ipad上的企鹅游戏,最后打算用留黑边来适配不同的屏幕。
一般来说对于4:3的屏幕都是上下黑边,2:1的屏幕都是左右黑边。如下图
大概的思路就是:按照开发的屏幕比例对比实际机型的屏幕比例来修改3DCamera和UICamera的ViewPortRect
1.首先获取两个比例,我这里是高宽比:
///
/// 开发屏幕的宽
///
public static float DevelopWidth = 1280f;
///
/// 开发屏幕的长
///
public static float DevelopHeigh = 720f;
///
/// 开发高宽比
///
public static float DevelopRate = DevelopHeigh /DevelopWidth;
///
/// 设备自身的高
///
public static int curScreenHeight = Screen.height;
///
/// 设备自身的高
///
public static int curScreenWidth = Screen.width;
///
/// 当前屏幕高宽比
///
public static float ScreenRate = (float)Screen.height / (float)Screen.width;
2.计算摄像机ViewPortRect中的实际宽高值:
///
/// 世界摄像机rect高的比例
///
public static float cameraRectHeightRate = DevelopHeigh / ((DevelopWidth / Screen.width) * Screen.height);
///
/// 世界摄像机rect宽的比例
///
public static float cameraRectWidthRate = DevelopWidth / ((DevelopHeigh / Screen.height) * Screen.width);
3.给每一个camera挂上脚本在Awake中调用FitCamera()
public void FitCamera(Camera camera)
{
///适配屏幕。实际屏幕比例<=开发比例的 上下黑 反之左右黑
if (DevelopRate <= ScreenRate)
{
camera.rect = new Rect(0, (1 - cameraRectHeightRate) / 2, 1, cameraRectHeightRate);
}
else
{
camera.rect = new Rect((1 - cameraRectWidthRate) / 2, 0, cameraRectWidthRate, 1);
}
}
4.给最外层的uicanvas挂上脚本调用FitCanvas
//适配uicanvas中的matchWidthOrHeight
public void FitCamera(Camera camera)
{
//适配屏幕。实际屏幕比例<=开发比例的,宽不变,高自适应,反之则不是
if (DevelopRate <= ScreenRate)
{
camera.rect = new Rect(0, (1 - cameraRectHeightRate) / 2, 1, cameraRectHeightRate);
}
else
{
camera.rect = new Rect((1 - cameraRectWidthRate) / 2, 0, cameraRectWidthRate, 1);
}
}