2016-08-24 125 views
1

我想異步加載本地圖像,但「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,它只顯示藍色圖像。

+0

請說明你是如何調用這段代碼所在的函數的。 –

+1

另外,你有沒有考慮嘗試擺脫'Texture2D紋理= ...'線,只是做'curTexture = www.texture;'? –

+1

您可以使用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

回答

2

正如我在評論說我會建議使用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; 
      } 
     } 
    } 
} 
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 
} 
+1

爲什麼while循環?只要'產生返回www;','WWW'類[支持返回一個產量](https://docs.unity3d.com/ScriptReference/WWW.html)。 –

+0

是的,你可以做到這一點,但我編輯它,使其更容易理解。 – Cabrra

+0

好吧,我現在看到評論(我確實想過),但是你仍然沒有解釋爲什麼你改變了它。 –