< Back to Game Dev, Unity

Filling the extra areas of the screen in Unity

A portrait game with a ratio of 4:3 fits perfectly on an ipad but on something like an iphone 5 that has a bigger height, there will be some empty space on the top and bottom. To fill up those spaces with a solid colour, make a ui image element, insert a square image, set it’s pivot point to the top or bottom and set it’s scale to 1,1 so it fills the width of the screen. Now you just have to set it’s height to the right ratio. Here’s the code for it:

//ratio of main game
float mainRatio = 4f/3f;
//get screen height based on this ratio
float screenMainRatioHeight = Screen.width * mainRatio;
//get the proportion of this height compared to the screen's height
float screenMainRatio = screenMainRatioHeight / (float)Screen.height;
//we want the remainder proportion after the main game's height is gone, divided by 2 because we have top and bottom
float yScale = (1 - screenMainRatio) / 2f;
//full screen the game object, then set the scale to what we calculated
gameObject.transform.localScale = new Vector2 (1,(float)Screen.height/(float)Screen.width);
gameObject.transform.localScale = new Vector2 (1,yScale*gameObject.transform.localScale.y);

Some things to note:

  • 4/3 would give 1 because both are integers so the result will be an integer so have to add the ‘f’ in.
  • UI Images use viewpoint coordinates so 0-1 as a fraction of it’s parent (though it seems to keep aspect ratio and not go larger than the screen size as a y scale of 1 does not stretch it to full height).
  • Setting the yScale to 1 doesn’t stretch it 100% of the screen’s height though (so have to scale it to full screen in the code)

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *