好久都没有更新新的东西了,现在看看之前写的东西突然想到还是记录一些什么吧,有些自己写的东西然后在这家公司写完了,下一家公司又要重新写一遍,不然的话就要把之前的项目工程下载下来在继续找之前写的东西,后来感觉特别不方便,还是把一些自己觉得共用的和常用的一些东西记录一下,方便自己查找也方便大家一起学习吧。
接下来是现在手机游戏各种各样的屏幕,针对这样的刘海屏等一些特殊的屏幕一些处理做一下适配的机制,思想是我们有时候要求刘海屏挡住的部分UI例如Button、Image希望根据刘海屏所在的位置下移或者上移,其实思想是一样的,就是根据UGUI的适配去考虑左上、上、右上、左下、下、右下这些适配的点的位置上移或者下移多少像素就可以了,接下来直接根据IPhoneX的适配为例子,写一个实例说明//UGUI适配方案(根据需求自定义)
//目前的需求不管什么手机背景全屏
//部分元素位置发生改变
public class UGUIAdaptation
{
private static readonly Vector2 Bottom = new Vector2(0.5f, 0);
private static readonly Vector2 LeftBottom = new Vector2(0, 0);
private static readonly Vector2 RightBottom = new Vector2(1, 0);
private static readonly Vector2 Top = new Vector2(0.5f, 1);
private static readonly Vector2 LeftTop = new Vector2(0, 1);
private static readonly Vector2 RightTop = new Vector2(1, 1);
[XLua.LuaCallCSharp]
public static void Adaptation(GameObject obj,int toppixel,int bottompixel,bool isstretching=false)
{
RectTransform rt = obj.GetComponent<RectTransform>();
int dir = GetDir(rt);
if (dir == -1)
return;
if (dir==0) //上
{
if (isstretching)
{
UIStretching(rt, toppixel);
}
else
{
TopAdaptationPosition(rt, toppixel);
}
}
else if (dir == 1)//下
{
if (isstretching)
{
UIStretching(rt, bottompixel);
}
else
{
BottomAdaptationPosition(rt, bottompixel);
}
}
}
//0上1下2左3右
private static int GetDir(RectTransform rt)
{
if (rt.anchorMin == Top || rt.anchorMin == LeftTop || rt.anchorMin == RightTop)
{
return 0;
}
if (rt.anchorMin == Bottom || rt.anchorMin == LeftBottom || rt.anchorMin == RightBottom)
{
return 1;
}
return -1;
}
private static void TopAdaptationPosition(RectTransform rt, int pixel)
{
rt.localPosition = new Vector3(rt.localPosition.x, rt.localPosition.y-pixel, rt.localPosition.z);
}
private static void BottomAdaptationPosition(RectTransform rt, int pixel)
{
rt.localPosition = new Vector3(rt.localPosition.x, rt.localPosition.y + pixel, rt.localPosition.z);
}
private static void UIStretching(RectTransform rt, int pixel)
{
rt.sizeDelta = new Vector2(rt.sizeDelta.x, rt.sizeDelta.y+ pixel);
}
}
这是我自己写的一个简单的示例思想,当然我觉得还有好多更好的解决方案,具体参数就是根据手机设备型号去判断是什么手机,然后大概上部和下部需要偏移的像素是多少传入对应的参数就好了。
这里提供一下IphoneX的判断参数依据:iPhone10,3|iPhone10,6|iPhone11,8|iPhone11,2|iPhone11,6这些都是需要处理的机型设备