LoginSignup
6
4

More than 5 years have passed since last update.

[Unity] RectTransformで特定方向にStretchしているかをスクリプト上で判定する

Last updated at Posted at 2017-01-31

RectTranformにおけるStretch状態

X軸に対するStretch

  • 横幅は親の横幅に依存して引き伸ばされる
  • PosXが指定出来なくなる代わりに、Right/Leftにマージンを指定可能になる
  • AnchorsのXの値が Min:0 / Max:1 になる
  • AnchorPresetsは以下のような状態になる (X軸が↔表示)

stretchx.png

Y軸に対するStretch

  • 縦幅は親の縦幅に依存して引き伸ばされる
  • PosYが指定出来なくなる代わりに、Top/Bottomにマージンを指定可能になる
  • AnchorsのYの値が Min:0 / Max:1 になる
  • AnchorPresetsは以下のような状態になる (Y軸が↔表示)

stretchy.png

XY軸に対するStretch

  • 横幅、縦幅共に親に依存して引き伸ばされる
  • AnchorsのX/Yの両値が Min:0 / Max:1 になる
  • AnchorPresetsは以下のような状態になる (XY軸が↔表示)

stretchxy.png

Stretch状態の判定処理

RectTransformOffsetChecker
using UnityEngine;

[RequireComponent(typeof(RectTransform))]
public class RectTransformOffsetChecker : MonoBehaviour
{
    void Start()
    {
        var rectTransform = this.GetComponent<RectTransform>();
        Debug.Log("anchorMin" + rectTransform.anchorMin);
        Debug.Log("anchorMax" + rectTransform.anchorMax);
    }
}

image

RectTransformを拡張して判定を行えるようにする

RectTransformExtension
using UnityEngine;

public static class RectTransformExtension
{
    public static bool IsStretchedX(this RectTransform rectTransform)
    {
        return rectTransform.anchorMin.x == 0 && rectTransform.anchorMax.x == 1;
    }

    public static bool IsStretchedY(this RectTransform rectTransform)
    {
        return rectTransform.anchorMin.y == 0 && rectTransform.anchorMax.y == 1;
    }

    public static bool IsStretchedXY(this RectTransform rectTransform)
    {
        return rectTransform.IsStretchedX() && rectTransform.IsStretchedY();
    }
}
RectTransformOffsetChecker
using UnityEngine;

[RequireComponent(typeof(RectTransform))]
public class RectTransformOffsetChecker : MonoBehaviour
{
    void Start()
    {
        var rectTransform = this.GetComponent<RectTransform>();
        Debug.Log("IsStretchedX" + rectTransform.IsStretchedX());
        Debug.Log("IsStretchedY" + rectTransform.IsStretchedY());
        Debug.Log("IsStretchedXY" + rectTransform.IsStretchedXY());
    }
}

image

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4