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!