Unity 读取本地文件夹图片

下面脚本实现的功能:

1.将本地图片(PNG和JPG)加载到UGUI上的Button的Image

2.用Scroll View组件自动排列

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;

public class Choose : MonoBehaviour
{
    private GameObject canvas;
    private Button _btn;
    private GameObject button;


    private List<Texture2D> images = new List<Texture2D>();

    void Start()
    {
        canvas = GameObject.Find("Canvas/Scroll View/Viewport/Content");

       
        load();

        for (int i = 0; i < images.Count; i++)
        {
            button = new GameObject("Button" + i, typeof(Button), typeof(RectTransform), typeof(Image));  //创建一个GameObject 加入Button组件

            button.transform.SetParent(this.canvas.transform);  //把Canvas设置成Button的父物体

            _btn = button.GetComponent<Button>();   //获得Button的Button组件

            //先创建一个Texture2D对象,用于把流数据转成Texture2D
            Sprite sprite = Sprite.Create(images[i], new Rect(0, 0, images[i].width, images[i].height), Vector2.zero);

            button.GetComponent<Image>().sprite = sprite;

            button.GetComponent<Button>().onClick.AddListener(ChooseButton);

        }
    }

    /// <summary>
    /// 加载文件夹内图片
    /// </summary>
    void load()
    {
        List<string> filePaths = new List<string>();

        string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
        string[] ImageType = imgtype.Split('|');

        for (int i = 0; i < ImageType.Length; i++)
        {
            //获取Application.dataPath文件夹下所有的图片路径  
            string[] dirs = Directory.GetFiles((Application.dataPath + "/Resources/Screenshot/"), ImageType[i]);
            for (int j = 0; j < dirs.Length; j++)
            {
                filePaths.Add(dirs[j]);
            }
        }

        for (int i = 0; i < filePaths.Count; i++)
        {
            Texture2D tx = new Texture2D(100, 100);
            tx.LoadImage(getImageByte(filePaths[i]));
            images.Add(tx);
        }
    }

    /// <summary>  
    /// 根据图片路径返回图片的字节流byte[]  
    /// </summary>  
    /// <param name="imagePath">图片路径</param>  
    /// <returns>返回的字节流</returns>  
    private static byte[] getImageByte(string imagePath)
    {
        FileStream files = new FileStream(imagePath, FileMode.Open);
        byte[] imgByte = new byte[files.Length];
        files.Read(imgByte, 0, imgByte.Length);
        files.Close();
        return imgByte;
    }

    public void ChooseButton()
    {
        //UGUI上Button按钮事件
        Debug.Log("按下了");
    }


}

发布了22 篇原创文章 · 获赞 6 · 访问量 1603

猜你喜欢

转载自blog.csdn.net/li1214661543/article/details/105437267