开发环境

  • Unity2021.3.39f1

代码

因为设备的纵横比例与开发环境的纵横比例是不同的,此时需要根据移动设备的纵横比例去调整CanvasScaler的Match参数,可获得最好的UI展示效果。

Unity的UICanvas适配设备分辨率 - 图1

代码是给竖屏做的适配。

Unity的UICanvas适配设备分辨率 - 图2

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// 自适应调整CanvasScale的Match
  7. /// </summary>
  8. [DisallowMultipleComponent]
  9. [RequireComponent(typeof(CanvasScaler))]
  10. public class AutoResolutionScaler : MonoBehaviour
  11. {
  12. [HideInInspector]
  13. public CanvasScaler BindCanvasScaler;
  14. [HideInInspector]
  15. public Vector2 DevelopReferenceResolution;
  16. [HideInInspector]
  17. public float DevelopResolutionRatio = 1;
  18. private void Awake()
  19. {
  20. BindCanvasScaler = GetComponent<CanvasScaler>();
  21. if (null == BindCanvasScaler)
  22. {
  23. Debug.LogError($"{gameObject.name} need CanvasScaler !");
  24. return;
  25. }
  26. if (BindCanvasScaler.uiScaleMode != CanvasScaler.ScaleMode.ScaleWithScreenSize)
  27. {
  28. Debug.LogError($"{gameObject.name} CanvasScaler uiScaleMode is not ScaleWithScreenSize !");
  29. return;
  30. }
  31. if (BindCanvasScaler.screenMatchMode != CanvasScaler.ScreenMatchMode.MatchWidthOrHeight)
  32. {
  33. Debug.LogError($"{gameObject.name} CanvasScaler screenMatchMode is not MatchWidthOrHeight !");
  34. return;
  35. }
  36. //x与y的比例
  37. DevelopReferenceResolution = BindCanvasScaler.referenceResolution;
  38. DevelopResolutionRatio = DevelopReferenceResolution.y / DevelopReferenceResolution.x;
  39. // 1920 / 1080 = 1.778
  40. // 2160 / 1440 = 1.5
  41. // 1280 / 720 = 1.778
  42. // 2340 / 1080 = 2.167
  43. float deviceResolutionRatio = Screen.height / Screen.width;
  44. if (deviceResolutionRatio >= DevelopResolutionRatio)
  45. {
  46. BindCanvasScaler.matchWidthOrHeight = 0;
  47. }
  48. else
  49. {
  50. BindCanvasScaler.matchWidthOrHeight = 1;
  51. }
  52. }
  53. }