[英]How can I load local images asynchronously?
I want to load a local image asynchronously, but "sprite.create" takes so much time which make my UI stop. 我想异步加载本地图像,但是“ sprite.create”花费了很多时间,这导致我的UI停止。 How can I fix this?
我怎样才能解决这个问题?
WWW www = new WWW (filePath);
yield return www;
Texture2D texture = new Texture2D(4, 4, TextureFormat.ARGB32, true);
www.LoadImageIntoTexture(texture);
www.Dispose ();
www = null;
curTexture = texture;
img.sprite = Sprite.Create (curTexture, new Rect (0, 0, curTexture.width, curTexture.height), new Vector2 (0.5f, 0.5f));
Update 2016.08.26: 更新2016.08.26:
I used RawImage to set texture instead of using Image which need to change texture to sprite. 我使用RawImage设置纹理,而不是使用需要将纹理更改为Sprite的Image。
Another question is that www.LoadImageIntoTexture is also take so much time. 另一个问题是www.LoadImageIntoTexture也花费了很多时间。 I used www.texture before, but I found it failed to load some png from android device which just display a blue image.
我以前使用过www.texture,但是我发现它无法从仅显示蓝色图像的android设备加载一些png。
As stated in my comment I would recommend using RawImage , which has a texture property , so you don't need to create a Sprite. 如我的评论所述,我建议您使用具有纹理属性的 RawImage ,因此您无需创建Sprite。
[SerializeField] private RawImage _rawImage;
public void DownloadImage(string url)
{
StartCoroutine(DownloadImageCoroutine(url));
}
private IEnumerator DownloadImageCoroutine(string url)
{
using (WWW www = new WWW(url))
{
// download image
yield return www;
// if no error happened
if (string.IsNullOrEmpty(www.error))
{
// get texture from WWW
Texture2D texture = www.texture;
yield return null; // wait a frame to avoid hang
// show image
if (texture != null && texture.width > 8 && texture.height > 8)
{
_rawImage.texture = texture;
}
}
}
}
Call a coroutine using this: 使用以下命令调用协程:
StartCoroutine(eImageLoad(filepath));
And here is the definition: 这是定义:
IEnumerator eImageLoad(string path)
{
WWW www = new WWW (path);
//As @ Scott Chamberlain suggested in comments down below
yield return www;
//This is longer but more explanatory
//while (false == www.isDone)
//{
// yield return null;
//}
//As @ Scott Chamberlain suggested in comments you can get the texture directly
curTexture = www.Texture;
www.Dispose ();
www = null;
img.sprite = Sprite.Create (curTexture, new Rect (0, 0, curTexture.width, curTe
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.