Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[RequireComponent (typeof (Canvas))]
[ExecuteInEditMode]
[AddComponentMenu("Layout/Physical Resolution", 102)]
public class PhysicalResolution : UIBehaviour
{
public enum Unit { Centimeters, Millimeters, Inches, Points, Picas }
[SerializeField] protected Unit m_Unit = Unit.Points;
public Unit unit { get { return m_Unit; } set { m_Unit = value; } }
[SerializeField] protected float m_DefaultDPI = 96;
public float defaultDPI { get { return m_DefaultDPI; } set { m_DefaultDPI = value; } }
private Canvas m_Canvas;
private float m_PrevDpi = -1;
protected PhysicalResolution()
{}
protected override void OnEnable()
{
m_Canvas = GetComponent<Canvas>();
SetScaleFactor();
}
protected virtual void Update()
{
SetScaleFactor();
}
protected virtual void SetScaleFactor()
{
float currentDpi = Screen.dpi;
if (m_Canvas == null || currentDpi == m_PrevDpi)
return;
m_PrevDpi = currentDpi;
float dpi = (currentDpi == 0 ? m_DefaultDPI : currentDpi);
float targetDPI = 1;
switch (m_Unit)
{
case Unit.Centimeters: targetDPI = 2.54f; break;
case Unit.Millimeters: targetDPI = 25.4f; break;
case Unit.Inches: targetDPI = 1; break;
case Unit.Points: targetDPI = 72; break;
case Unit.Picas: targetDPI = 6; break;
}
m_Canvas.scaleFactor = dpi / targetDPI;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment