Created
August 11, 2015 22:20
-
-
Save RyanNielson/c36ac6093c7ce45b8468 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
/// <summary> | |
/// Letterboxes the view to the aspect ratio given in targetSize. | |
/// If stretch is true, view fills camera with given aspect ratio. | |
/// If stretch is false, view is letterboxed to sizes that are only *1, *3, *3, etc of targetSize. | |
/// </summary> | |
[ExecuteInEditMode, RequireComponent(typeof(Camera))] | |
public class LetterboxAndScale : MonoBehaviour | |
{ | |
public Vector2 targetSize = new Vector2(400, 240); | |
private new Camera camera; | |
public bool stretch = true; | |
private void Awake() | |
{ | |
camera = GetComponent<Camera>(); | |
} | |
private void Start() | |
{ | |
AddLetterbox(); | |
} | |
private void Update() | |
{ | |
AddLetterbox(); | |
} | |
private void AddLetterbox() | |
{ | |
Rect cameraRect = camera.rect; | |
if (stretch) | |
{ | |
float targetAspectRatio = targetSize.x / targetSize.y; | |
float windowAspectRatio = Screen.width / (float)Screen.height; | |
float scaleHeight = windowAspectRatio / targetAspectRatio; | |
if (scaleHeight < 1f) | |
{ | |
cameraRect.width = 1f; | |
cameraRect.height = scaleHeight; | |
cameraRect.x = 0; | |
cameraRect.y = (1f - scaleHeight) / 2f; | |
} | |
else | |
{ | |
float scaleWidth = 1f / scaleHeight; | |
cameraRect.width = scaleWidth; | |
cameraRect.height = 1f; | |
cameraRect.x = (1f - scaleWidth) / 2f; | |
cameraRect.y = 0; | |
} | |
camera.rect = cameraRect; | |
} | |
else | |
{ | |
int nearestWidth = Mathf.FloorToInt(Screen.width / targetSize.x) * (int)targetSize.x; | |
int nearestHeight = Mathf.FloorToInt(Screen.height / targetSize.y) * (int)targetSize.y; | |
int xScaleFactor = Mathf.FloorToInt(nearestWidth / targetSize.x); | |
int yScaleFactor = Mathf.FloorToInt(nearestHeight / targetSize.y); | |
int scaleFactor = yScaleFactor < xScaleFactor ? yScaleFactor : xScaleFactor; | |
Vector2 scaled = targetSize * scaleFactor; | |
cameraRect.width = scaled.x / Screen.width; | |
cameraRect.height = scaled.y / Screen.height; | |
cameraRect.x = (1f - cameraRect.width) / 2f; | |
cameraRect.y = (1f - cameraRect.height) / 2f; | |
camera.rect = cameraRect; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment