回到顶部

Unity3D结合NGUI的屏幕自适应代码分享

时间:4年前   作者:CnctSoft   浏览:421   [站内原创,转载请注明出处]

标签: Unity3D  

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人立场,如涉及侵权,请及时告知。

评论努力加载中...
暂无评论
暂无评论

手机扫码阅读

热门相关

加载中...
关于我们   联系我们   申请友链   赞助记录   站点地图
© 2014 - 2017 www.80iter.com All Rights Reserved. 京ICP备14042174号-1
本站遵循 CC BY 4.0 协议,转载请注明出处 。