hello!
i'm using unity and the following script on my camera to have a fixed aspect ratio
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class CameraCrop : MonoBehaviour {
// Set this to your target aspect ratio, eg. (16, 9) or (4, 3).
public Vector2 targetAspect = new Vector2(16, 9);
Camera _camera;
void Start () {
_camera = GetComponent<Camera>();
UpdateCrop();
}
// Call this method if your window size or target aspect change.
public void UpdateCrop() {
// Determine ratios of screen/window & target, respectively.
float screenRatio = Screen.width / (float)Screen.height;
float targetRatio = targetAspect.x / targetAspect.y;
if(Mathf.Approximately(screenRatio, targetRatio)) {
// Screen or window is the target aspect ratio: use the whole area.
_camera.rect = new Rect(0, 0, 1, 1);
}
else if(screenRatio > targetRatio) {
// Screen or window is wider than the target: pillarbox.
float normalizedWidth = targetRatio / screenRatio;
float barThickness = (1f - normalizedWidth)/2f;
_camera.rect = new Rect(barThickness, 0, normalizedWidth, 1);
}
else {
// Screen or window is narrower than the target: letterbox.
float normalizedHeight = screenRatio / targetRatio;
float barThickness = (1f - normalizedHeight) / 2f;
_camera.rect = new Rect(0, barThickness, 1, normalizedHeight);
}
}
}
well, the field camera is going weel but i ahev some issues with my ui camera where i need to resize a SpriteRenderer background to fit the entire camera viewport, to do this i'm using the following function
void ResizeSpriteToScreen()
{
SpriteRenderer sr = sprite.GetComponent<SpriteRenderer>();
sprite.transform.position = _myCamera.transform.position + Vector3.forward * sr.transform.position.z;
sprite.transform.localScale = new Vector3(1, 1, 1);
Vector3 lossyScale = sprite.transform.lossyScale;
float width = sr.sprite.bounds.size.x;
float height = sr.sprite.bounds.size.y;
float worldScreenHeight = _myCamera.orthographicSize * 2f;
float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
Vector3 xWidth = sprite.transform.localScale;
xWidth.x = worldScreenWidth / width;
sprite.transform.localScale = xWidth;
//transform.localScale.x = worldScreenWidth / width;
Vector3 yHeight = sprite.transform.localScale;
yHeight.y = worldScreenHeight / height;
sprite.transform.localScale = yHeight;
Vector3 newLocalScale = new Vector3(transform.localScale.x / lossyScale.x,
sprite.transform.localScale.y / lossyScale.y,
sprite.transform.localScale.z / lossyScale.z
);
sprite.transform.localScale = newLocalScale;
}
before the CameraCrop component was working well to resize my Sprite, but now i got a sprite resized to stay inside the black bar on 4:3 for example.. i need to have my spriterender resized properly to fit the entire screen in any aspect ratio that i will set, anyone can help me to figure out how to do this?
thank's in advance