0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】再帰的に親のCanvasサイズを取得する

Posted at

TL;DR

大体の場合はrectTransform.rect.sizeを使えばいい

はじめに

uGUIで要素の大きさを取得する方法は2つあります。

  • RectTransform.sizeDelta
    • アンカー間の距離と比較したRectTransformのサイズ
    • アンカーが一致していれば要素のサイズと同じ
    • アンカーが離れている場合(Stretch)は親との相対距離
  • RectTransform.rect
    • Transform のローカル空間で計算された矩形

大体の場合はrectTransform.rect.sizeを使えばいいのですが、何らかの影響で取得できない場合がありました。uGUIでAnchorが一致していない場合(=Stretch)は親の座標から相対的にサイズが決定するため、再帰的に自身の大きさを取得するコードを書いてみました。

コード

.cs
    static Vector2 GetRectSize(RectTransform self)
    {
        var parent = self.parent as RectTransform;
        if (parent == null)
        {
            return new Vector2(self.rect.width, self.rect.height);
        }
        // 枝切り処理。これはない方がよい場合もある。
        if (parent.anchorMin == parent.anchorMax)
        {
            return parent.sizeDelta;
        }
        var parentSize = GetRectSize(parent);
        var anchor = self.anchorMax - self.anchorMin;
        var width = (parentSize.x * anchor.x) + self.sizeDelta.x;
        var height = (parentSize.y * anchor.y) + self.sizeDelta.y;
        return new Vector2(width, height);
    }

最後に

あんまり使うことないと思いますが、折角書いたのでよかったら使ってください…。CC0です。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?