Files
Dontback/Assets/Scripts/Camera/ScreenAspect.cs
2024-09-09 20:30:24 +08:00

44 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
namespace Camera
{
public class ScreenAspect : MonoBehaviour
{
//目标比例默认16:9
public float TargetAspect = 16f / 9f;
private UnityEngine.Camera _mainCamera;
private void Awake()
{
_mainCamera = UnityEngine.Camera.main;
var windowAspect = Screen.width / (float)Screen.height;
var scaleHeight = windowAspect / TargetAspect;
if (scaleHeight < 1f)
{
var rect = _mainCamera.rect;
rect.width = 1f;
rect.height = scaleHeight;
rect.x = 0;
rect.y = (1f - scaleHeight) / 2f;
_mainCamera.rect = rect;
}
else
{
var scaleWidth = 1f / scaleHeight;
var rect = _mainCamera.rect;
rect.width = scaleWidth;
rect.height = 1f;
rect.x = (1f - scaleWidth) / 2f;
rect.y = 0;
_mainCamera.rect = rect;
}
}
}
}