如何异步加载本地图像?
我想异步加载本地图像,但“sprite.create”需要很长时间才能停止UI。我怎样才能解决这个问题?如何异步加载本地图像?
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));
更新2016年8月26日:
我用RawImage设置的纹理,而不是使用Image这就需要改变纹理精灵。
另一个问题是,www.LoadImageIntoTexture也需要这么多时间。我以前使用过www.texture,但是我发现它无法从Android设备加载一些png,它只显示蓝色图像。
正如我在评论说我会建议使用RawImage,其中有一个texture property,所以你不”需要创建一个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;
}
}
}
}
呼叫使用该协程:
StartCoroutine(eImageLoad(filepath));
这里的定义是:
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
}
为什么while循环?只要'产生返回www;','WWW'类[支持返回一个产量](https://docs.unity3d.com/ScriptReference/WWW.html)。 –
是的,你可以做到这一点,但我编辑它,使其更容易理解。 – Cabrra
好吧,我现在看到评论(我确实想过),但是你仍然没有解释为什么你改变了它。 –
请说明你是如何调用这段代码所在的函数的。 –
另外,你有没有考虑尝试摆脱'Texture2D纹理= ...'线,只是做'curTexture = www.texture;'? –
您可以使用UI.RawImage而不是UI.Image,并直接将[WWW.texture](https://docs.unity3d.com/ScriptReference/WWW-texture.html)分配给[RawImage.texture](http:/ /docs.unity3d.com/ScriptReference/UI.RawImage-texture.html) – JeanLuc