Scaling Images to full screen in Unity

Posted on

in

,

First, you’d put the image into your scene and give it a name, in this case “mainStage”. Then in the code:

float worldScreenHeight = Camera.main.orthographicSize * 2;
        float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

        mainStage = GameObject.Find ("mainStage");
        SpriteRenderer sr = mainStage.GetComponent<SpriteRenderer>();

        mainStage.transform.localScale = new Vector2(
            worldScreenWidth / sr.sprite.bounds.size.x,
            worldScreenHeight / sr.sprite.bounds.size.y);

Though, this isn’t very practical as it would stretch your image. A more likely thing you’d want is to scale your background image to fit the width of the screen and then scale the height by the same amount. Is this case, transform would look something like:

mainStage.transform.localScale = new Vector2(
            worldScreenWidth / sr.sprite.bounds.size.x,
            worldScreenWidth * 4/3sr.sprite.bounds.size.y);

Here, I am using a 4:3 ratio so it goes full screen on something like an ipad

Leave a Reply

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

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031