Unity3d 手机屏幕自动适配

现在,市场上的手机分辨率多样化。带给开放人员一个很大的“跨界问题”。本人,昨晚突发奇想。手机分辨率多样化,但手机开放人员,制作UI时,最为重要的两个因素就是Position(位置)、Scale(大小);

我引入一个“比例”概念;

比例:

原始开放的平台手机分辨率为960*640,一个GameObject:Position(300,100,0),Scale(100,100,1);

那么“移植”到 800*480手机上;

“比例”:RatioV3(800/960,480/640,1);

次GameObject在800*480手机为:Position(249,75,0),Scale(83,75,1);

效果还算是比较理想;

代码如下:

publicclass _Public : MonoBehaviour {

public    static Vector3  helfScreen;

  Vector3  initScreen=new Vector3 (480,320,1);

public  static  Vector3  ratioScreen;

 

// Use this for initialization

void Awake () {

getScreen();

}

public   void getScreen(){

 

if(helfScreen==Vector3.zero){

helfScreen.x=(float)(Screen.width/2);

helfScreen.y=(float)(Screen.height/2);

helfScreen.z=1f;

}

if(ratioScreen==Vector3.zero){

float  x= helfScreen.x/ initScreen.x;

float  y= helfScreen.y / initScreen.y;

ratioScreen.x=float.Parse(x.ToString("F2"));

ratioScreen.y=float.Parse(y.ToString("F2"));

ratioScreen.z=1f;

}

 

}

}

.81640625public class _ScreenFit : MonoBehaviour {

[System.Serializable]

public  class  ScreenFit{

public  Transform   fitTrans;

public  bool isFitScale=true;

 

public void initFit(){

//  Fit Position

if(fitTrans==null)return ;

 

Vector3 position=fitTrans.localPosition;

position.x*=_Public.ratioScreen.x;

position.y*=_Public.ratioScreen.y;

position.z*=_Public.ratioScreen.z;

fitTrans.localPosition=position;

 

// Fit Scale

if(isFitScale){

 

Vector3 scale=fitTrans.localScale;

if(scale==Vector3.one){

scale.y*=_Public.ratioScreen.y;

scale.x*=_Public.ratioScreen.y;

scale.z*=_Public.ratioScreen.z;

//scale.x*=_Public.ratioScreen.x;

}

else {

scale.x*=_Public.ratioScreen.x;

scale.y*=_Public.ratioScreen.y;

scale.z*=_Public.ratioScreen.z;

}

fitTrans.localScale=scale;

 

}

}

}

public  ScreenFit[]   screenFitS;

public   Transform  backTrans;

    

// Use this for initialization

void Start () {

initScreenFit();

}

 

void initScreenFit(){

foreach(ScreenFit  screenFit in screenFitS){

screenFit.initFit();

}

 

if(backTrans==null) return ;

Vector3 scale=backTrans.localScale;

scale.x=_Public.helfScreen.x*2;

scale.y=_Public.helfScreen.y*2;

backTrans.localScale=scale;

 

}

}

 

效果图如下:960*480

800*480下

posted @ 2013-03-11 11:55  韦斯利yx  阅读(2628)  评论(0编辑  收藏  举报