- Home /
How do I draw controls in a GUI Window - based on screen dimensions?
It seems that whenever I try to code any GUI stuff that should theoretically work, Unity doesn't like it. In the Script Reference, they tell you how to draw Controls, but they only use integer values. However, I'd like the buttons inside to change position relative to the Screen Resolution, but it doesn't really work. Any ideas?
Code:
var w : int;
var h : int;
var csw : float;
var csh : float;
function Update()
{
w = Screen.width;
h = Screen.height;
csw = w*0.9;
csh = h*0.9;
}
function OnGUI()
{
if(ButtonMaker.clickedButton == 1){
GUI.Window(0,Rect(w/10,h/10,w*0.8,h*0.8),MultiMenu,"Multiplayer Menu");
}
}
function MultiMenu(windowID : int)
{
if(GUI.Button(Rect(csw-32,csh,32,32),"",close))
{
freezeMainMenu = false;
ButtonMaker.clickedButton = 0;
}
}
In the line"if(GUI.Button(Rect(csw-32,csh,32,32),"",close))" which should render a Button, the button doesn't appear, but if I used only integer values ins$$anonymous$$d, it would appear.
Answer by Fabkins · Apr 28, 2012 at 12:27 PM
What I do is use co-ordinates based on a percentage of the screen rather than absolute position. So I've this utility function to create me a Rect:
function SR( x: float, y: float, width: float, height: float)
{
return ( Rect ( Screen.width *x, Screen.height *y,
Screen.width * width, Screen.height *height) );
}
Anytime I want to place a GUI item I then do something like:
GUILayout.BeginArea ( SR(0.1,0.5,0.8,0.2))
This for example will create an area that uses most of the screen at is 10% (0.1) in on the left and is 80% (0.8) of the screen width.
Thats all well and good but then for things like buttons its no good as it depends on the apsect ratio. ie the button will be a strange shape the screen is landscape vs portrait.
So for buttons / labels I do something a bit different. I have a function that basically uses the a percentage of the largest of either width or height.
function SP( size: float)
{
if ( Screen.width > Screen.height)
{
return( Screen.width * size);
}
else
{
return( Screen.height * size);
}
}
I can use that with buttons like this:
GUI.Button(Rect( SP(0.025),SP(0.025), SP(0.08), SP(0.08) ),buttonIcon);
As long as the aspect ratio generally stays the same the system works well. ie 3:2 or 4:3 in either orientation are close enough. Screens wont be identical between a 3:2 and 4:3 device buts its close enough.
I have an App that displays things correctly on retina display iPad and iPhone as well as non-retina display iPhone and iPad in either landscape or portrait orientation. Looks good on the computer screen as well.