diff --git a/ScreenAspect/README.md b/ScreenAspect/README.md new file mode 100644 index 0000000..dacd6b4 --- /dev/null +++ b/ScreenAspect/README.md @@ -0,0 +1,2 @@ +public float TargetAspect = 16f / 9f; +修改以上数值即可设置相机比例。 \ No newline at end of file diff --git a/ScreenAspect/ScreenAspect.cs b/ScreenAspect/ScreenAspect.cs new file mode 100644 index 0000000..e65ed5c --- /dev/null +++ b/ScreenAspect/ScreenAspect.cs @@ -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; + } + } + } +} \ No newline at end of file