simplestarの技術ブログ

目的を書いて、思想と試行、結果と考察、そして具体的な手段を記録します。

Unity:4画面テクスチャビューアの配置スクリプト

画像処理していると、複数枚のテクスチャを見比べたりしていきたいところなのですが
Android 環境にもっていくと、配置がずれていたりして困ったことになったので
簡単な配置スクリプトを作りました。

自分が再利用する目的で記事書きます。

f:id:simplestar_tech:20170402153656j:plain

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIQuadViewBehaviour : MonoBehaviour {

    public enum QuadLocation
    {
        LeftTop = 0,
        LeftBottom,
        RightTop,
        RightBottom
    }

    public QuadLocation MyLocation;

	// Use this for initialization
	void Start () {
        ResizeLocate();
    }
	
	// Update is called once per frame
	void Update () {
    }

    private void ResizeLocate()
    {
        int width = Screen.width / 2;
        int height = Screen.height / 2;

        Vector3 location = Vector3.zero;

        switch (MyLocation)
        {
            case QuadLocation.LeftTop:
                location.x = -width / 2;
                location.y = height / 2;
                break;
            case QuadLocation.LeftBottom:
                location.x = -width / 2;
                location.y = -height / 2;
                break;
            case QuadLocation.RightTop:
                location.x = width / 2;
                location.y = height / 2;
                break;
            case QuadLocation.RightBottom:
                location.x = width / 2;
                location.y = -height / 2;
                break;
            default:
                break;
        }

        RectTransform rc = GetComponent<RectTransform>();

        rc.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
        rc.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
        rc.localPosition = location;
    }
}

UI の RawImage にこのスクリプトコンポーネントを付けると、起動時に画面4分割の配置に移動します。
Anchor Presets は center と middle の組み合わせに限ります。

PC でテストして Android で実行するとビューが壊れているなんていう問題は、一応これで回避
テクスチャの解像度やアスペクト比まで考えて、賢く配置してくれと言いたい文句もありますが、そこはテクスチャをセットする側が調整してあげて…