using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class DemoTest : MonoBehaviour
{
string url = @"E:/simulator/Assets/Images/details/btn_go.png";
[SerializeField] private Image im;
// Start is called before the first frame update
void Start()
{
// Texture2D t = new Texture2D(1,1);
// t.LoadImage(ReadTexture(url));
// Sprite spr = Sprite.Create(t, new Rect(0,0,t.width,t.height), new Vector2(10.0f,10.0f));
// im.sprite = spr;
StartCoroutine(LoadTexture(url));
}
// Update is called once per frame
void Update()
{
}
#region 方法一:通过文件流(System.IO)的形式加载
/// <summary>
/// 文件路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private byte[] ReadTexture(string path){
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
//创建文件长度buffer
byte[] b = new byte[fileStream.Length];
fileStream.Read(b,0,(int)fileStream.Length);
fileStream.Close();
fileStream.Dispose();
fileStream = null;
return b;
}
#endregion
#region 方法二:通过UnityWebRequest加载
IEnumerator LoadTexture(string url){
var uri = new Uri(Path.Combine(url));
UnityWebRequest uwr = UnityWebRequest.Get(uri);
DownloadHandlerTexture tex = new DownloadHandlerTexture(true);
uwr.downloadHandler = tex;
yield return uwr.SendWebRequest();
if(uwr.isHttpError || uwr.isNetworkError){
Debug.LogError(uwr.error);
}
else{
Texture2D t2d = new Texture2D(1,1);
t2d = tex.texture;
Sprite spr = Sprite.Create(t2d, new Rect(0,0,t2d.width,t2d.height), new Vector2(0.5f,0.5f));
im.sprite = spr;
}
}
#endregion
}
Unity 加载图片的两种方式文件流和UnityWebRequest
最新推荐文章于 2024-07-06 09:37:51 发布