Unity 選択した画像をscrollViewで表示
画像を選択して、大きい画像には、スクロールバーで表示できるコードを作ったよ。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public class ScrollPicture : MonoBehaviour
{
private Texture2D loadTexture;
private Vector2 scrollViewVector = new Vector2(0,0);
public Rect scrollViewRect1;
public Rect scrollViewRect2;
void Start()
{
//スタート時(宣言時×)に値を格納しないと、コードを更新してもpubulicの値が変わらなくなる。
//第3引数、第4引数はScrollView自体の表示範囲。scrollViewRect2が範囲を超えるとスクロールバーが付く。
scrollViewRect1 = new Rect (20, 80, 450, 300);
}
private void OnGUI()
{
if (GUI.Button(new Rect(15, 20, 100, 50), "画像選択"))
{
//画像のパスを取得。
var sourcePath = EditorUtility.OpenFilePanel("Select Image", "", "png,jpg,jpeg");
if (!string.IsNullOrEmpty(sourcePath))
{
//画像のサイズは自由(LoadImage時に自然に変わる)
loadTexture = new Texture2D(0, 0);
loadTexture.LoadImage(System.IO.File.ReadAllBytes(sourcePath));
}
}
if (loadTexture != null)
{
//ロードした画像の情報を変数に格納。
var rect = GUILayoutUtility.GetRect(loadTexture.width, loadTexture.height, GUILayout.MaxWidth(loadTexture.width), GUILayout.MaxHeight(loadTexture.height));
//第3,4引数はScrollViewの中身の表示範囲。
scrollViewRect2 = new Rect (0, 0, loadTexture.width, loadTexture.height);
//スクロールビューを表示する。
scrollViewVector = GUI.BeginScrollView (scrollViewRect1, scrollViewVector, scrollViewRect2);
//画像を描画する。
EditorGUI.DrawTextureTransparent(rect, loadTexture);
}
// スクロールビューを終了する。
GUI.EndScrollView();
}
}
お名前
