如何异步加载本地图像?

时间:2016-08-24 13:05:14

标签: c# unity3d

我想异步加载本地图像,但是" 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.08.26:

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

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

2 个答案:

答案 0 :(得分:2)

如我的评论中所述,我建议使用RawImage texture property,因此您不需要创建精灵。

[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;
            }
        }
    }
}

答案 1 :(得分:1)

使用以下方法调用协程:

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
}