Unity dynamically loads local images and typesetting functions

 

Load local image function interface

public void LoadLocalTextures(){

string imgType="*.BMP|*.JPG|*.PNG";    //需要加载的图片类型后缀
string[] imgTypes=imgType.Split('|');
   for (int i = 0; i < ImgType.Length; i++)
            {
                string[] s2 = Directory.GetFiles(PictureStr, ImgType[i]);    //PictureStr 为图片所在路径
                for (int ji = 0; ji < s2.Length; ji++)
                {
                    GameObject ga = Instantiate(Picture_Button, Picture_Grid.transform) as GameObject;    //创建button实例,父节点为网格组件

//文件流读取图片
                    FileStream fileStream = new FileStream(s2[ji], FileMode.Open, FileAccess.Read);

                    byte[] bytes = new byte[fileStream.Length];

                    fileStream.Read(bytes, 0, (int)fileStream.Length);


                    fileStream.Close();

                    fileStream.Dispose();
                    fileStream = null;
//设置图片大小
                    int width = 400;
                    int height = 400;
//创建texture2D
                    Texture2D texture = new Texture2D(width, height);
//加载图片流
                    texture.LoadImage(bytes);
//创建sprite并赋值
                    Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    ga.GetComponent<Image>().sprite = sprite;
                }

            }
}

Grid button automatic layout:

UI level

Picture_ScrollView object adds scrollRect component

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AutoSortGrid : MonoBehaviour
{
    private RectTransform[] GradChildRectTrans;
    private float targetWidth, targetHeight, gridWidth, gridHeight, cellSizeX, cellSizeY, spacingX, spacingY;
    int gridChildCount = 0;

    public void UpdateAutoSort()
    {

        gridWidth = GetComponent<RectTransform>().rect.width;
        gridHeight = GetComponent<RectTransform>().rect.height;
        cellSizeX = GetComponent<GridLayoutGroup>().cellSize.x;
        cellSizeY = GetComponent<GridLayoutGroup>().cellSize.y;
        spacingX = GetComponent<GridLayoutGroup>().spacing.x;
        spacingY = GetComponent<GridLayoutGroup>().spacing.y;
        if (transform.childCount > 0)
        {
            gridChildCount = transform.childCount;

            int x = (int)(gridWidth / (spacingX + cellSizeX));
            int yCount = gridChildCount / x;
            float yHeight = (spacingY + cellSizeY) * yCount;

            if (yHeight > gridHeight)
            {
                transform.GetComponent<RectTransform>().sizeDelta = new Vector2(gridWidth, yHeight + 500f);
            }

        }
    }

}

 

Guess you like

Origin blog.csdn.net/qq_40097668/article/details/113990089