Unity外部异步加载图片(附排序)

将图片完全路径加载到内存中,这个过程很快,完全不会卡顿。当需要使用图片时,再执行加载图片的方法,每次加载3-4张图(一块屏幕显示三四张图也差不多了吧),用户几乎完全不会有感觉。

上代码:

 /// <summary>
    /// 统一异步载入
    /// </summary>
    public async void UniteFSAsync()
    {
        dirInfo = new DirectoryInfo(Application.streamingAssetsPath + "/加载图片的路径");

        FileInfo[] files;

        string[] ImgType = "*.jpg|*.png|*.bmp".Split('|');

        Debug.Log(dirInfo);

        for (int j = 0; j < ImgType.Length; j++)
        {
            files = dirInfo.GetFiles(ImgType[j]);

            for (int i = 0; i < files.Length; i++)
            {
               
                GameObject tf = Instantiate(Resources.Load("预制体名字"), 父类Transform) as GameObject;

                保存预制体的数组.Add(tf);

                Debug.log( files[i].FullName);//文件全名称
                

                //await LoadByFSAsync(files[i].FullName, raw);//加载图片的方法
            }
        }
    }

 下面是加载图片的方法,可以调整为等比例显示。

/// <summary>
    /// 异步载入图片
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="image">Image对象</param>
    /// <returns></returns>
    private async Task LoadByFSAsync(string path, RawImage image)
    {
        byte[] result;

        using (FileStream SourceStream = File.Open(path, FileMode.Open))
        {
            result = new byte[SourceStream.Length];
            await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
        }

        Texture2D tx = new Texture2D(2, 1);

        tx.LoadImage(result);

        //等比例调整图片大小
        //float widthRatio = tx.width / img_width;
        //float heightRatio = tx.height / img_height;

        //if (widthRatio / heightRatio > 1.1)
        //{
        //    image.GetComponent<RectTransform>().sizeDelta = new Vector2(tx.width / widthRatio, tx.height / widthRatio);
        //}
        //else
        //{
        //    image.GetComponent<RectTransform>().sizeDelta = new Vector2(tx.width / heightRatio, tx.height / heightRatio);
        //}

        image.texture = tx;
    }

再来一个是加载好的图片顺序不对,图片1后面是图片10,而不是2,解决方案就是弄个排序。

public class FileNameSort : IComparer
{
    //调用DLL
    [System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
    private static extern int StrCmpLogicalW(string param1, string param2);


    //前后文件名进行比较。
    public int Compare(object name1, object name2)
    {
        if (null == name1 && null == name2)
        {
            return 0;
        }
        if (null == name1)
        {
            return -1;
        }
        if (null == name2)
        {
            return 1;
        }
        return StrCmpLogicalW(name1.ToString(), name2.ToString());
    }
}

//使用时   Array.Sort(文件名, new FileNameSort());

Guess you like

Origin blog.csdn.net/hp150119/article/details/121859034