Skip to content

Instantly share code, notes, and snippets.

@baobao baobao/UGUIBgFit.cs

Created Jun 25, 2016
Embed
What would you like to do?
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode ()]
[RequireComponent (typeof(RectTransform))]
/// <summary>
/// アタッチしたRectTransformを画面にフィットさせます
/// </summary>
public class UGUIBgFit : MonoBehaviour
{
private float _imgRatio;
[SerializeField]
private CanvasScaler _scaler;
[SerializeField]
private RectTransform _rectTr;
private void Start ()
{
if (_scaler == null) {
_scaler = GetComponentInParent<CanvasScaler> ();
}
if (_rectTr == null) {
_rectTr = GetComponent<RectTransform> ();
}
Fit ();
}
private void Update ()
{
#if UNITY_EDITOR
// Edit中でも反映されます
Fit ();
#endif
}
private void Fit ()
{
if (_rectTr == null || _scaler == null) {
return;
}
float screenW = (float)Screen.width;
float screenH = (float)Screen.height;
var screenRatio = screenW / screenH;
_imgRatio = _rectTr.sizeDelta.x / _rectTr.sizeDelta.y;
if (_imgRatio <= screenRatio) {
// 画面が横長
_scaler.referenceResolution = new Vector2 (screenW, screenW);
_rectTr.sizeDelta = new Vector2 (screenW, screenW / _imgRatio);
_scaler.matchWidthOrHeight = 0;
} else {
// 画面が縦長
_scaler.referenceResolution = new Vector2 (screenH, screenH);
_rectTr.sizeDelta = new Vector2 (screenH * _imgRatio, screenH);
_scaler.matchWidthOrHeight = 1f;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.