基于NGUI的屏幕自适应

using UnityEngine;
using System.Collections;

public class MyStrech : MonoBehaviour {


    /// <summary>
    /// 默认对齐方式
    /// </summary>
    public Agin agin = Agin.Center;
    /// <summary>初始缩放值</summary>
    public float scale_base;
    /// <summary> 默认宽度</summary>
    public float base_width;
    
    public float base_height;

    //记录上次宽高,
    public int last_width;
    public int last_height;

    /// <summary>
    /// 对齐方式
    /// </summary>
    public enum Agin { 
        Width,
        Height,
        Center
    }

    // Use this for initialization
    void Start () {
        reset();
    }
    
    // Update is called once per frame
    void Update () {
        //宽高改变之后进行自适应
        if (Screen.width != last_width || Screen.height != last_height) {
            reset();
            last_width = Screen.width;
            last_height = Screen.height;
        }
    }

    void reset() {
        float value = Screen.height / base_height;

        switch (agin) { 
            case Agin.Center:
                if (Screen.width / base_width < Screen.height / base_height)
                {
                    gameObject.transform.localScale = new Vector3(scale_base * (Screen.width / base_width) / value, scale_base * Screen.width / base_width / value, scale_base * Screen.width / base_width / value);
                }
                else {
                    gameObject.transform.localScale = new Vector3(scale_base, scale_base, scale_base);
                }
                break;
            case Agin.Height:
                gameObject.transform.localScale = new Vector3(scale_base, scale_base, scale_base);
                break;
            case Agin.Width:
                gameObject.transform.localScale = new Vector3(scale_base * (Screen.width / base_width) / value, scale_base * Screen.width / base_width / value, scale_base * Screen.width / base_width / value);
                break;
        }
    }
}

 

posted @ 2015-11-28 02:02  bambom  阅读(160)  评论(0编辑  收藏  举报