-
-
Save capnslipp/9619297 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @source: https://gist.github.com/darktable/2018687#file-guiscaler-cs | |
using System; | |
using System.Collections; | |
using UnityEngine; | |
/// Usage: | |
/// (optional) Call GUIScaler.Initialize() in Start(), Awake() or OnEnable() (only needed once) | |
/// Call GUIScaler.Begin() at the top of your OnGUI() methods | |
/// Call GUIScaler.End() at the bottom of your OnGUI() methods | |
/// | |
/// WARNING: If you don't match Begin() and End() strange things will happen. | |
public static class GUIScaler | |
{ | |
// 163 is the dpi of the 1st generation iPhone, a good base value. | |
const float BASE_SCALE = 163.0f; | |
static bool _initialized = false; | |
static bool _isScaling = false; | |
static float _scale = 1f; | |
public static float scale { | |
get { return _scale; } | |
} | |
static Matrix4x4 _restoreMatrix = Matrix4x4.identity; | |
/// Initialize the GUI scaler with a specific scale. | |
public static void Initialize(float scale) | |
{ | |
if (_initialized) | |
return; | |
else | |
_initialized = true; | |
// scale will be 0 on platforms that have unknown dpi (usually non-mobile) | |
if (scale == 0f) { | |
return; | |
} | |
else { | |
_scale = scale; | |
_isScaling = true; | |
} | |
} | |
/// Initialize the GUI scaler using the detected screen dpi. | |
public static void Initialize() | |
{ | |
Initialize(Screen.dpi / BASE_SCALE); | |
} | |
/// All GUI elements drawn after this will be scaled. | |
public static void BeginScale() | |
{ | |
if (!_initialized) | |
Initialize(); | |
if (!_isScaling) | |
return; | |
_restoreMatrix = GUI.matrix; | |
GUI.matrix = GUI.matrix * Matrix4x4.Scale(new Vector3(_scale, _scale, _scale)); | |
} | |
/// Restores the default GUI scale. | |
/// All gui elements drawn after this will not be scaled. | |
public static void EndScale() | |
{ | |
if (!_isScaling) | |
return; | |
GUI.matrix = _restoreMatrix; | |
} | |
public static void Scale(Action contentsBlock) { | |
BeginScale(); | |
contentsBlock(); | |
EndScale(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment