相机比例

This commit is contained in:
2024-07-10 17:01:32 +08:00
parent 15c2849090
commit 4722df04fd
2 changed files with 46 additions and 0 deletions

2
ScreenAspect/README.md Normal file
View File

@@ -0,0 +1,2 @@
<code>public float TargetAspect = 16f / 9f;</code>
修改以上数值即可设置相机比例。

View File

@@ -0,0 +1,44 @@
using UnityEngine;
namespace AnnoyingUtils.ScreenAspect
{
public class ScreenAspect : MonoBehaviour
{
//目标比例默认16:9
public float TargetAspect = 16f / 9f;
private Camera _mainCamera;
private void Awake()
{
_mainCamera = 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;
}
}
}
}