LoginSignup
12
13

More than 5 years have passed since last update.

Unity2Dで画面のアスペクト比を固定にしたい【Unity, uGUI】

Last updated at Posted at 2015-08-02

以前の投稿では単なるSpriteだったので、今回はuGUIでアスペクト比を固定にします。

今回使用する画像

前回と同じ画像です。
640✕940の画像
cd1e292c-f081-94d8-b351-ea17208ae8df.png

配置

Hierarchy→UI→Image でGameObjectを配置します。
スクリーンショット 2015-08-02 16.22.52.png

画面に対してはみ出しまくってます。
スクリーンショット 2015-08-02 18.27.40.png

画面にフィットさせる

今回の縦横はピクセル数になっているので以前に比べると簡単です。

AspectKeeper.cs
public bool isUpdate = false;

private RectTransform _rt;
private Vector2 _originSizeDelta;
private float _aspect;
private float _screenAspect;

void Start () {
    _rt =  GetComponent<RectTransform>();
    _originSizeDelta = _rt.sizeDelta;
    _aspect = _rt.sizeDelta.x / _rt.sizeDelta.y;

    keepAspect();
}

void Update () {
    if (isUpdate)
        keepAspect();
}

private void keepAspect() {
    _rt.anchoredPosition = Vector2.zero;

    _screenAspect = (float)Screen.width / (float)Screen.height;
    // 画像のアスペクト比と画面のアスペクト比を比較します
    if (_aspect > _screenAspect) {
        // 縦長の画面の時
        float w = (float)Screen.width;
        float h = w / _aspect;
        _rt.sizeDelta = new Vector2(w, h);
    } else {
        // 横長の画面の時
        float h = (float)Screen.height;
        float w = h * _aspect;
        _rt.sizeDelta = new Vector2(w, h);
    }
}

このスクリプトをuGUIのGameObjectに貼り付けると、アスペクト比を保ってくれます。
Untitled.gif

12
13
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
12
13