Unity 笔记-- 读取StreamingAssets文件夹下Texture图片

1.声明变量UnityWebRequest 为UWR

2.使用UnityWebRequestTexture下载图片,并将下载信息保存到UWR

UWR= UnityWebRequestTexture.GetTexture(Path);

        Path为图片所在位置路径(Application.streamingAssetsPath + "/IMG_0206.JPG")

       在下载时注意检查下载地址是否存在(使用File时需要引用   IO)using System.IO;

if (File.Exists(Path))
   {
    Debug.Log(Path + "地址存在");
    
   }
else
    {
      Debug.Log(Path + "地址不存在");
    }

3.当图片下载完成后继续,

        UnityWebRequest.Result.ProtocolError //检查下载是否有错误

4.使用DownloadHandlerTexture.GetContent(UWR) 将下载的图片信息装换为Textuer 

Texture2D texture = DownloadHandlerTexture.GetContent(UWR);

        textrue 为声明的Texture 用于接收下载后的图片信息

5.使用 Sprite.Create 将下载后的Texture文件转换为Sprite文件

Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1f)

        Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1f);//将Texture转为Sprite 

          texture 需要转换的Txture 图片 

           Rect(开始x坐标,开始y坐标,图片宽度,图片高度)      

            Vector2.zero  轴

             1f 像素

6.将转换完成的Sprite赋值给Image

        image.sprite = sprite;

7.根据图片修改Image的大小

image.rectTransform.sizeDelta = new Vector2(texture.width, texture.height);//调整UI image大小为图片大小

8. 使用File保存Textrue图片到StreamingAssets

File.WriteAllBytes(Application.streamingAssetsPath + "/w.jpg", texture.EncodeToJPG());//将下载的图片保存到本地

        注意保存图片的格式和Texture.EncodeToJPG,保持一致

使用UnityWebRequest 下载图片

 IEnumerator IEnReadTexture()
    {
          Texture2D texture;
         
        UnityWebRequest UWR = UnityWebRequestTexture.GetTexture(Path);
        yield return UWR.SendWebRequest();
        if (UWR.result != UnityWebRequest.Result.ProtocolError)
        {
            texture = DownloadHandlerTexture.GetContent(UWR);
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1f);//将Texture转为Sprite 
            //image.rectTransform.sizeDelta = new Vector2(texture.width, texture.height);//调整UI image大小为图片大小
            image.sprite = sprite;
        }
        yield return new WaitForSeconds(3);
       
    }

猜你喜欢

转载自blog.csdn.net/qq_36361484/article/details/125716911
今日推荐