SafeCanvas.cs 765 B

123456789101112131415161718192021
  1. using UnityEngine;
  2. namespace DiamondArrow
  3. {
  4. public sealed class SafeCanvas : MonoBehaviour
  5. {
  6. public RectTransform content;
  7. void LateUpdate() { Apply(); }
  8. public void Apply()
  9. {
  10. if (!content) return;
  11. var area = Screen.safeArea;
  12. if (area.width <= 0 || area.height <= 0) return;
  13. float canvasScale = Mathf.Max(.001f, GetComponent<Canvas>().scaleFactor);
  14. float fit = Mathf.Min(area.width / 750f, area.height / 1334f);
  15. content.sizeDelta = area.size / fit;
  16. content.localScale = Vector3.one * (fit / canvasScale);
  17. content.anchoredPosition = (area.center - new Vector2(Screen.width, Screen.height) * .5f) / canvasScale;
  18. }
  19. }
  20. }