栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

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

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

上代码:

 /// 
    /// 统一异步载入
    /// 
    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);//加载图片的方法
            }
        }
    }

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

/// 
    /// 异步载入图片
    /// 
    /// 路径
    /// Image对象
    /// 
    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().sizeDelta = new Vector2(tx.width / widthRatio, tx.height / widthRatio);
        //}
        //else
        //{
        //    image.GetComponent().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());

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901211.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号