0
0

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 1 year has passed since last update.

SetNativeSize()をした時に画像の位置が変わってしまうのを修正する拡張クラス

Last updated at Posted at 2022-07-18

はじめに

Imageのスプライトを動的に変更したい時、サイズ感(見た目)が変わる時に便利なのがSetNativeSize()

ただ、SetNativeSize()を実行すると位置がずれてしまうので、煩わしいこと考えずにスプライト変更できる拡張クラスを紹介します。

目次

  1. コード
  2. 解説
  3. 使い方
  4. 参考文献

コード

ImageExt.cs
using UnityEngine;
using UnityEngine.UI;

public static class ImageExt
{
    public static void SetNativeSizeOriginPos(this Image self)
    {
        var originalSize = self.rectTransform.sizeDelta;
        var sizeRate = self.rectTransform.localScale;
        Vector3 offsetSize;

        self.SetNativeSize();
        offsetSize = (originalSize - self.rectTransform.sizeDelta) * sizeRate;
        self.rectTransform.localPosition -= offsetSize / 2;
    }
}

解説

元の画像サイズを取得し、SetNativeSize()した後に元の画像サイズと現在の画像サイズの差分を計算。
最後に差分の半分の値を現在の位置に引く。


使い方

Sample.cs
using UnityEngine;
using UnityEngine.UI;

public static class Sample : MonoBehaviour
{
    [SerializeField] private Image _image;
    [SerializeField] private Sprite _sprite;

  
    void Start()
    { 
         _image.sprite = _sprite;
         _image.SetNativeSizeOriginPos(); 
    }
}

スプライトを変更した後に呼び出すだけ。(SetNativeSize()を同じ要領)

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?