好久都沒有更新新的東西了,現在看看之前寫的東西突然想到還是記錄一些什麼吧,有些自己寫的東西然後在這家公司寫完了,下一家公司又要重新寫一遍,不然的話就要把之前的項目工程下載下傳下來在繼續找之前寫的東西,後來感覺特别不友善,還是把一些自己覺得共用的和常用的一些東西記錄一下,友善自己查找也友善大家一起學習吧。
接下來是現在手機遊戲各種各樣的螢幕,針對這樣的劉海屏等一些特殊的螢幕一些處理做一下适配的機制,思想是我們有時候要求劉海屏擋住的部分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這些都是需要處理的機型裝置