加载外部图片的三种方法

一、 WWW 加载
首先,获取当前工程同目录下的“MapImages”文件夹路径,然后获取每张图片的全部路径,并将路径存到列表中。
[csharp]  view plain  copy
  1. /// <summary>  
  2.    /// 获取当前物体应该读取的地形贴图的文件的路径  
  3.    /// </summary>  
  4.    /// <returns></returns>  
  5.    private string GetFilePath()  
  6.    {  
  7.        string[] strTempPath = Application.dataPath.Split('/');  
  8.        string strPath = string.Empty;  
  9.        //去掉后面两个,获取跟工程相同目录的路径,如“E:/ZXB/MyProject/Asset/",去掉后面两个就得到和工程同级的目录为:“E:/ZXB”  
  10.        for (int i = 0; i < strTempPath.Length - 2; i++)  
  11.        {  
  12.            strPath += strTempPath[i] + "/";  
  13.        }  
  14.        //加上整个地形贴图的文件命  
  15.        strPath += TERRAINMAP_FILENAME + "/";  
  16.        //最后加上当前文件夹的名称,最后的文件夹名称和当前物体的名称一致  
  17.        strPath += gameObject.name + "/";  
  18.   
  19.        return strPath;  
  20.    }  
  21.    /// <summary>  
  22.    /// 获取所有地图贴图文件路径  
  23.    /// </summary>  
  24.    /// <param name="info"></param>  
  25.    private void GetAllFile(FileSystemInfo info)  
  26.    {  
  27.        if (!info.Exists)  
  28.        {  
  29.            Debug.Log("该路径不存在!");  
  30.            return;  
  31.        }  
  32.        DirectoryInfo dir = info as DirectoryInfo;  
  33.        if (null == dir)  
  34.        {  
  35.            Debug.Log("该目录不存在!");  
  36.            return;  
  37.        }  
  38.        FileSystemInfo[] si = dir.GetFileSystemInfos();  
  39.        for (int i = 0; i < si.Length; i++)  
  40.        {  
  41.            FileInfo fi = si[i] as FileInfo;  
  42.            if (null != fi && IsImage(fi.Extension))  
  43.            {  
  44.                listStrFileName.Add(fi.FullName);  
  45.            }  
  46.            else  
  47.            {  
  48.   
  49.            }  
  50.        }  
  51.    }  

然后根据路径列表使用WWW逐个加载图片
[csharp]  view plain  copy
  1. /// <summary>  
  2.    /// 根据文件路径加载图片  
  3.    /// </summary>  
  4.    private IEnumerator GetAllTexture()  
  5.    {  
  6.        curFilePath = GetFilePath();  
  7.        DirectoryInfo tempInfo = new DirectoryInfo(curFilePath);  
  8.        GetAllFile(tempInfo);  
  9.        foreach (string item in listStrFileName)  
  10.        {  
  11.            WWW www = new WWW("file://" + item);  
  12.            yield return www;  
  13.            //先得到最后的图片文件名  
  14.            string[] tempAllFileName = item.Split(Path.DirectorySeparatorChar);  
  15.            //去掉后缀  
  16.            string tempStrKey = tempAllFileName[tempAllFileName.Length - 1];  
  17.            tempStrKey = tempStrKey.Substring(0, tempStrKey.Length - 4).Trim();  
  18.            if (null != tempStrKey && !dicTextures.ContainsKey(tempStrKey))  
  19.            {  
  20.                dicTextures.Add(tempStrKey, www.texture);  
  21.            }  
  22.            else  
  23.            {  
  24.                Debug.LogError("图片文件名为空或者有相同的文件名!");  
  25.                continue;  
  26.            }  
  27.            if (dicSubTerrainMat.ContainsKey(tempStrKey))  
  28.            {  
  29.                dicSubTerrainMat[tempStrKey].SetTexture("_MainTex", www.texture);  
  30.            }  
  31.            else  
  32.            {  
  33.                Debug.LogError("文件名" + tempStrKey + "在材质列表中没有找到对应的材质名!");  
  34.            }  
  35.        }  
  36.        isLoadAllTexture = true;  
  37.        Debug.Log("Load All Terrain Texture!");  
  38.    }  
效果图如图所示:一开始显示的是默认模糊处理的贴图,在加载的过程中帧率非常低,造成卡顿。

二、 IO 文件流加载

        首先,同样的是加载文件路径。然后开启另外一个线程将图片的字节流加载到字典中。
[csharp]  view plain  copy
  1. /// <summary>  
  2.    /// 根据文件路径读取图片并转换成byte  
  3.    /// </summary>  
  4.    /// <param name="path"></param>  
  5.    /// <returns></returns>  
  6.    public static byte[] ReadPictureByPath(string path)  
  7.    {  
  8.        FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);  
  9.        fileStream.Seek(0, SeekOrigin.Begin);  
  10.        byte[] binary = new byte[fileStream.Length];  
  11.        fileStream.Read(binary, 0, (int)fileStream.Length);  
  12.        fileStream.Close();  
  13.        fileStream.Dispose();  
  14.        fileStream = null;  
  15.        return binary;  
  16.    }  
  17.    然后,加载整个文件列表里的图片到字典缓存中。  
  18.    /// <summary>  
  19.    /// 根据文件路径加载图片  
  20.    /// </summary>  
  21.    private void GetAllTerrainTex()  
  22.    {  
  23.        DirectoryInfo tempInfo = new DirectoryInfo(curFilePath);  
  24.        GetAllFile(tempInfo);  
  25.        foreach (string item in listStrFileName)  
  26.        {  
  27.            byte[] tempImageBuffer = ReadPictureByPath(item);  
  28.            if (null == tempImageBuffer)  
  29.            {  
  30.                Debug.Log("读取路径" + item + "图片失败!");  
  31.            }  
  32.            string[] tempAllFileName = item.Split(Path.DirectorySeparatorChar);  
  33.            //去掉后缀  
  34.            string tempStrKey = tempAllFileName[tempAllFileName.Length - 1];  
  35.            tempStrKey = tempStrKey.Substring(0, tempStrKey.Length - 4).Trim();  
  36.            if (null != tempStrKey && !dicImageBuffer.ContainsKey(tempStrKey))  
  37.            {  
  38.                dicImageBuffer.Add(tempStrKey, tempImageBuffer);  
  39.            }  
  40.            else  
  41.            {  
  42.                Debug.LogError("图片文件名为空或者有相同的文件名!");  
  43.                continue;  
  44.            }  
  45.        }  
  46.        isLoadAllTexture = true;  
  47.        Debug.Log("Load All Terrain Texture!");  
  48.    }  

最终的加载效果图如图所示:同样会导致帧率很低造成卡顿,但是这种方式有一个好处是可以先将图片使用其他线程加载到缓存中,造成卡顿是因为将字节流转成Texture2D
 
[csharp]  view plain  copy
  1. Texture2D tempTex = new Texture2D(TERRAIN_MAP_DI, TERRAIN_MAP_DI);  
  2.              tempTex.LoadImage(item.Value);  

这里的地形贴图都很大,就算单张图片压缩到 4M 左右,使用 LoadImage 方法还是会卡顿。而这个方法又只能在主线程里使用,也即不能在新开的加载线程里使用。 Unity 对这类的类都限制了,只能在主线程使用。
三、 Assetbundle 打包再加载
    首先,要将贴图导入到 Unity 工程里面,然后对一个文件夹里的贴图进行打包。 .0 之后的打包方式比较简单,如图所示:
 
先选中要打包的贴图,在 Inspectors 面板下有个 AssetBundle ,这里新建你要打包成集合的名字,我以文件夹的名字新建了一个标签“ 40_73.4_36.69237_77.61875” 。选中文件夹里其他图片,将它们都设置成这个标签。这样就可以将整个文件夹里的图片打包成一个集合,方便一次性加载。

        打包的代码和简单,可以在 Editor 文件下,创建一个编辑脚本,代码如下:
[csharp]  view plain  copy
  1. [MenuItem("Example/Build Asset Bundles")]  
  2.     static void BuildABs()  
  3.     {  
  4.         // Put the bundles in a folder called "ABs" within the Assets folder.  
  5.         BuildPipeline.BuildAssetBundles("Assets/Assetbundle", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);  
  6.     }  

对比以前的方式,新的打包方法确实简化方便了很多。接下来将打包好的Assetbundle文件夹放到工程的同级目录下,加载Assetbuudle的代码如下:
[csharp]  view plain  copy
  1. /// <summary>  
  2.     ///异步加载地形的贴图  
  3.     /// </summary>  
  4.     /// <returns></returns>  
  5.     private IEnumerator SetAllTexAsy()  
  6.     {  
  7.         yield return null;  
  8.         var bundleLoadRequest = AssetBundle.LoadFromFileAsync(curFilePath);  
  9.         yield return bundleLoadRequest;  
  10.         var myLoadedAssetBundle = bundleLoadRequest.assetBundle;  
  11.         if (myLoadedAssetBundle == null)  
  12.         {  
  13.             Debug.Log("Failed to load AssetBundle!");  
  14.             yield break;  
  15.         }  
  16.         foreach (var item in dicSubTerrainMat)  
  17.         {  
  18.             var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<Texture2D>(item.Key);  
  19.             yield return assetLoadRequest;  
  20.   
  21.             Texture2D tempTex = assetLoadRequest.asset as Texture2D;  
  22.             if (null == tempTex)  
  23.             {  
  24.                 Debug.Log(gameObject.name + "Assetbundle里没有对应" + item.Key + "的贴图");  
  25.             }  
  26.             else  
  27.             {  
  28.                 item.Value.SetTexture("_MainTex", tempTex);  
  29.             }  
  30.         }  
  31.         myLoadedAssetBundle.Unload(false);  
  32.     }  
加载得到集合包,然后根据每个图片的文件名得到具体的图片。最终的效果图如图所示:
可以看到帧率几乎不受任何影响,但是会在加载到显示的过程中停留2秒时间左右,对于程序的卡顿,这个时间的停滞还是可以接受的。
四、总结
虽然,第三种方式在加载的时候比较流畅,不会影响到主线程的执行。但是,打包的过程也是一个很繁琐,且需要细致认真的工作。总的来说第三种方式最好的,前面两种方式应该用在其他方面,或许以后就能用的上。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值