Scale Sprite to Fullscreen: Perspective Camera

Hi Guys,

I’m trying to scale a image (UI 4.6 ) to fit the screen width/height of the viewport.

I have existing code to do this with the orthographic camera:

    public bool SetInitialSize()
    {
        SpriteRenderer sr = GetComponent<SpriteRenderer>();

        if (sr)
        {
            Camera cam;
            if (cam = GameObject.Find("MapViewCamera").GetComponent<Camera>())
            {
                float worldScreenHeight = (float)(cam.orthographicSize * 2.0);
                float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
                float newLocalScale = (worldScreenWidth / sr.sprite.bounds.size.x);

                transform.localScale = new Vector3(newLocalScale, newLocalScale, 1);
                SetScaleClamp(transform.localScale);

                Vector3 position;
                position.x = cam.transform.position.x - (sr.bounds.size.x * 0.5f);
                position.y = cam.transform.position.y - (sr.bounds.size.y * 0.5f);
                position.z = transform.position.z;
                transform.position = position;
            }
            else
            {
                Debug.Log("MapHandler::SetInitialSize() - Camera not found as parent to Map Object!");
                return false;
            }
        }
        else
        {
            Debug.Log("MapHandler::SetInitialSize() - SpriteRenderer Component not found!");
            return false;
        }
        return true;
    }

However I have no idea about the maths for doing this with a perspective camera. I’ve google’d around, and people only seem to mention orthographic. I understand it’d be based by distance from the camera, however what’s the equation? Does anyone have sample code?

Thanks!

Well if it is ui 4.6 then it is on canvas which is on camera and it doesn’t matter type of camera or size right?

Yeah that sounds right to me phoda… The problem is how do I calculate from there?

The only measurements I see I can take are orthographicSize, pixelHeight, and Screen.Height… When I put them into the equation, like so:

if (image)
        {

            float worldScreenHeight = (float)(Screen.height);
            float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
            float newLocalScale = (worldScreenWidth / image.sprite.bounds.size.x);
            transform.localScale = new Vector3(newLocalScale, newLocalScale, 1);
        }

The image ends up being about x10 the size of the viewport…

Any thoughts?

Thanks!

Seems like a cheat, but for anyone curious about how I got around this. I simply added a AspectRatioFitter from the layout section to a parent of the Image. I then set the aspect ratio high enough in width that it’d always appear fully no matter what the screen size… Although it’s not mathematically flush, it works…

hehe there ar no cheats in game making. If it works its good if not then find another way

1 Like