Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[code] Auto-Rescale GUI Elements. (without stretch)

Discussion in 'Immediate Mode GUI (IMGUI)' started by krisu, Sep 9, 2013.

  1. krisu

    krisu

    Joined:
    Jul 10, 2013
    Posts:
    40
    Hello.
    I just show simple code,
    how make auto-rescale Gui elements without stretching, also doing auto-center. (something similar is in FlashPlayer).

    Code (csharp):
    1.  
    2. public  static void     BeginFixedSize(float sw,float sh,float vw,float vh)
    3. {
    4.         float sAspect = sw/sh, vAspect = vw/vh, scl = sw/vw;
    5.         if(sAspect > vAspect) scl = sh/vh;
    6.         GUI.matrix = Matrix4x4.TRS(new Vector3((sw - vw*scl)*0.5f,(sh - vh*scl)*0.5f,0),Quaternion.identity,new Vector3(scl,scl,1));
    7. }
    8. public  static void     EndFixedSize()
    9. {
    10.         GUI.matrix = Matrix4x4.TRS(Vector3.zero,Quaternion.identity,Vector3.one);
    11. }
    12.  
    Example:
    Code (csharp):
    1.  
    2. void OnGUI()
    3. {
    4.     BeginFixedSize(Screen.width,Screen.height,800,600);
    5.         // now you need enter 800-20 instead Screen.width-20, same with height.
    6.  
    7.         GUI.Label(new Rect(100,100,200,40),"Hello World");
    8.         GUI.Label(new Rect(800-20,600-20,200,40),"END");
    9.     EndFixedSize();
    10. };
    11.