如何用unitask加载本地图片
时间: 2023-03-26 18:00:26 浏览: 296
您可以使用以下代码来使用unitask加载本地图片:
```csharp
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using Cysharp.Threading.Tasks;
public class LoadLocalImage : MonoBehaviour
{
public Image image;
async void Start()
{
string path = Application.streamingAssetsPath + "/image.png";
byte[] bytes = await ReadAllBytesAsync(path);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(bytes);
image.sprite = Sprite.Create(texture, new Rect(, , texture.width, texture.height), Vector2.zero);
}
async UniTask<byte[]> ReadAllBytesAsync(string path)
{
using (FileStream sourceStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true))
{
var buffer = new byte[sourceStream.Length];
await sourceStream.ReadAsync(buffer, , (int)sourceStream.Length);
return buffer;
}
}
}
```
其中,image是一个UI Image组件,用于显示加载的图片。path是本地图片的路径,可以根据实际情况进行修改。使用UniTask的ReadAllBytesAsync方法来异步读取本地图片的字节数据,然后使用Texture2D.LoadImage方法将字节数据转换为Texture2D,最后使用Sprite.Create方法创建一个Sprite并将其设置为Image的sprite属性,从而显示加载的图片。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)