如何异步加载本地图像?

本文关键字:地图 图像 加载 何异步 异步 | 更新日期: 2023-09-27 18:03:58

我想异步加载一个本地图像,但是"sprite "。"创建"需要花费太多时间,这让我的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.08.26:

我使用RawImage来设置纹理,而不是使用需要将纹理更改为精灵的Image。

另一个问题是www.LoadImageIntoTexture也花了这么多时间。我以前使用www.texture,但我发现它无法从android设备加载一些png,只是显示一个蓝色的图像。

如何异步加载本地图像?

正如我在评论中所说,我建议使用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;
            }
        }
    }
}

调用协程:

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
}