Unity3D結合NGUI的螢幕自適應程式碼分享

CnctSoft發表於2019-05-11

using UnityEngine;
using System.Collections;
public class CalculateScreen : MonoBehaviour {

	public UIRoot uiRoot = null;//繫結NGUI的Root層
	public UISprite mBackgroundSprite=null;//繫結背景Sprite層
	public UISprite mFullScreenSprite = null; //繫結需要全屏的Sprite層
	private const int cDesignWidth = 2560;//最大設計螢幕Width
	private const int cDesignHeight = 1440;//最大設計螢幕Hight
	private int mRealScreenWidth = 0;
	private int mRealScreenHeight = 0;
	private readonly float mWidthScale = ConvertHelper.ToFloat(Screen.width,0) / cDesignWidth;
	private readonly float mHeightScale = ConvertHelper.ToFloat(Screen.height,0) / cDesignHeight;
	// Use this for initialization
	void Awake(){
		CalculateScreenWidthHeight();
	}
	void Start () {
		AdaptiveManualHeight(uiRoot);
		AdaptiveBackgroundSprite(mBackgroundSprite);
		AdaptiveFullScreenSprite(mFullScreenSprite);
	}
 	private void CalculateScreenWidthHeight(){
		float scale = (float)uiRoot.activeHeight/Screen.height;
		mRealScreenWidth = Mathf.CeilToInt(Screen.width*scale);
		mRealScreenHeight = Mathf.CeilToInt(Screen.height*scale);
	}

	public void AdaptiveManualHeight(UIRoot root){
		if(ConvertHelper.ToFloat(Screen.height,0)/Screen.width>ConvertHelper.ToFloat(cDesignHeight,0)/cDesignWidth){
			root.manualHeight = Mathf.RoundToInt(ConvertHelper.ToFloat(cDesignWidth,0)/Screen.width*Screen.height);
		}else{
			root.manualHeight = cDesignHeight;
		}
	}

	public void AdaptiveBackgroundSprite(UISprite backgroundSprite){
		if(mRealScreenWidth>backgroundSprite.width||mRealScreenHeight>backgroundSprite.height){
			int adaptiveHeight = Mathf.RoundToInt(cDesignHeight*mHeightScale);
			int adaptiveWidth = Mathf.RoundToInt(cDesignWidth*mHeightScale);
			if(mHeightScale<=mWidthScale){
				adaptiveHeight = Mathf.RoundToInt(cDesignHeight*mWidthScale);
				adaptiveWidth = Mathf.RoundToInt(cDesignWidth*mWidthScale);
			}
			backgroundSprite.SetDimensions(adaptiveWidth,adaptiveHeight);
		}
	}

	public void AdaptiveFullScreenSprite(UISprite fullScreenSprite){
		fullScreenSprite.SetDimensions(mRealScreenWidth,mRealScreenHeight);
	}

	// Update is called once per frame
	void Update () {
	
	}
}



內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章