Skip to content

Instantly share code, notes, and snippets.

@ateliee
Last active October 14, 2018 01:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ateliee/73ecdfe3ca86962b8c1926425f34a22e to your computer and use it in GitHub Desktop.
Save ateliee/73ecdfe3ca86962b8c1926425f34a22e to your computer and use it in GitHub Desktop.
UnityでSafeAreaをエディタ上に表示するMonoBehaviour
using UnityEngine;
using System.Collections;
/// <summary>
/// SafeAreaの反映
/// </summary>
[ExecuteInEditMode]
public class SafeArea : MonoBehaviour
{
private RectTransform rectTransform;
/// <summary>
/// iPhoneXのサイズ
/// </summary>
private const float safeAreaEnableAspect = (float)1125 / 2436;
/// <summary>
/// The top area rate.
/// </summary>
private const float topAreaRate = 0.04f;
/// <summary>
/// The bottom area rate.
/// </summary>
private const float bottomAreaRate = 0.06f;
/// <summary>
/// エディタ上でリアルタイム反映させたい場合
/// </summary>
[SerializeField]
private bool isEnableEditor = true;
void Awake()
{
rectTransform = GetComponent<RectTransform>();
Debug.Assert(rectTransform != null, "Not Attach");
}
// Update is called once per frame
void Update()
{
ApplySafeArea();
}
private void ApplySafeArea(){
var area = GetSafeArea();
var anchorMin = area.position;
var anchorMax = area.position + area.size;
anchorMin.x /= Screen.width;
anchorMin.y /= Screen.height;
anchorMax.x /= Screen.width;
anchorMax.y /= Screen.height;
rectTransform.anchorMin = anchorMin;
rectTransform.anchorMax = anchorMax;
}
private Rect GetSafeArea()
{
var rect = Screen.safeArea;
#if UNITY_EDITOR
if(isEnableEditor){
var screenAspect = (float)Screen.width / Screen.height;
// 表示サイズによって若干の誤差が生まれるので少し修正
screenAspect *= 0.95f;
if(screenAspect <= safeAreaEnableAspect){
// デバッグ用に設定
var top = rect.height * topAreaRate;
var bottom = rect.height * bottomAreaRate;
rect.y = bottom;
rect.height = rect.height - top - bottom;
}
}
#endif
return rect;
}
}
@ateliee
Copy link
Author

ateliee commented Oct 13, 2018

Canvas直下にEmptyなContentを設置し、SafeAreaをアタッチしてください。

iPhoneXより細長い端末サイズであればSafeArea分小さくなります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment