No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CustomCanvasScaler.cs 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #if UGUI_1_0_0_OR_NEWER
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. public class CustomCanvasScaler : CanvasScaler
  5. {
  6. private Canvas m_RootCanvas;
  7. private const float kLogBase = 2;
  8. protected override void OnEnable()
  9. {
  10. m_RootCanvas = GetComponent<Canvas>();
  11. base.OnEnable();
  12. }
  13. protected override void HandleScaleWithScreenSize()
  14. {
  15. Vector2 screenSize;
  16. if (m_RootCanvas.worldCamera != null)
  17. {
  18. screenSize = new Vector2(m_RootCanvas.worldCamera.pixelWidth, m_RootCanvas.worldCamera.pixelHeight);
  19. }
  20. else
  21. {
  22. screenSize = new Vector2(Screen.width, Screen.height);
  23. }
  24. // Multiple display support only when not the main display. For display 0 the reported
  25. // resolution is always the desktops resolution since its part of the display API,
  26. // so we use the standard none multiple display method. (case 741751)
  27. int displayIndex = m_RootCanvas.targetDisplay;
  28. if (displayIndex > 0 && displayIndex < Display.displays.Length)
  29. {
  30. Display disp = Display.displays[displayIndex];
  31. screenSize = new Vector2(disp.renderingWidth, disp.renderingHeight);
  32. }
  33. float scaleFactor = 0;
  34. switch (m_ScreenMatchMode)
  35. {
  36. case ScreenMatchMode.MatchWidthOrHeight:
  37. {
  38. // We take the log of the relative width and height before taking the average.
  39. // Then we transform it back in the original space.
  40. // the reason to transform in and out of logarithmic space is to have better behavior.
  41. // If one axis has twice resolution and the other has half, it should even out if widthOrHeight value is at 0.5.
  42. // In normal space the average would be (0.5 + 2) / 2 = 1.25
  43. // In logarithmic space the average is (-1 + 1) / 2 = 0
  44. float logWidth = Mathf.Log(screenSize.x / m_ReferenceResolution.x, kLogBase);
  45. float logHeight = Mathf.Log(screenSize.y / m_ReferenceResolution.y, kLogBase);
  46. float logWeightedAverage = Mathf.Lerp(logWidth, logHeight, m_MatchWidthOrHeight);
  47. scaleFactor = Mathf.Pow(kLogBase, logWeightedAverage);
  48. break;
  49. }
  50. case ScreenMatchMode.Expand:
  51. {
  52. scaleFactor = Mathf.Min(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
  53. break;
  54. }
  55. case ScreenMatchMode.Shrink:
  56. {
  57. scaleFactor = Mathf.Max(screenSize.x / m_ReferenceResolution.x, screenSize.y / m_ReferenceResolution.y);
  58. break;
  59. }
  60. }
  61. SetScaleFactor(scaleFactor);
  62. SetReferencePixelsPerUnit(m_ReferencePixelsPerUnit);
  63. }
  64. }
  65. #endif