2014-01-27 23 views
3

我有從Facebook獲取的圖像url,我想在我的遊戲中的libgdx.i中使用facebook圖形api顯示該圖像,並在Json解析的幫助下解析數據。我的做法如下:Libgdx在運行時從Facebook獲取圖像

在主要活動

protected void gettingfacebookData() { 
    try { 
     JSONArray friendArray = new JSONArray(
       prefLevel.getFriendFacebookData()); 
     for (int i = 0; i < friendArray.length(); i++) { 
      JSONObject jsonObject = friendArray.getJSONObject(i); 

      String name = jsonObject.getString("name"); 
      String score = jsonObject.getString("score"); 
      String fid = jsonObject.getString("fid"); 
      String image = "http://graph.facebook.com/" + fid 
        + "/picture?type=large"; 
//saving score into array list 
      PlayingScreen.scoreAl.add(score); 
//saving image url into arraylist 
      PlayingScreen.imageUrlAl.add(image); 

      }   } 

     } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

現在,我怎麼在運行時顯示的圖像與該特定圖像的URL?

回答

1
  1. 您應該下載圖像。
  2. 一旦你有你的字節數組圖像,你可以創建一個像素映射: Pixmap pixmap = new Pixmap(imageBytes, 0, imageBytes.length);

  3. 然後你就可以使用這個像素圖來呈現圖像。例如,如果你使用scene2d.ui您可以設置圖片的繪製如下:

image.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(profilePicture))));

希望這有助於。

+0

這實際上是我現在在做什麼,但我得到漸進式JPEG圖像錯誤的錯誤,當時我的比賽開始落後,因爲我只能保存URL不下載圖像,並開始像在運行時下載這導致滯後:( –

+0

你在桌面上或Android上進步jpeg錯誤? – ilkinulas

+0

我得到這個錯誤在Android –

2

我們使用包裝類,包裝Texture,用於顯示來自網站的圖像(如Facebook個人資料圖片)。這個包裝類獲取圖像的URL和臨時紋理。就像創建包裝器一樣,它開始在後臺線程中下載圖像字節。這個包裝類的使用者只需調用getTexture()即可獲取紋理,直到下載完成,此方法返回臨時紋理。當有字節可用來創建紋理時getTexture()處理這些字節並開始返回由url創建的新紋理。

下面是這個包裝類的簡單版本。請注意,processTextureBytesgetTexture方法內部調用,而不是在後臺線程中的某處。這是因爲我們必須在獲得GLContext的線程中構造紋理。您可以將緩存和重試機制添加到此類。

順便說一句,而不是使用http://graph.facebook.com/[uid]/picture網址嘗試使用從FQLpic_網址之一。你可能想檢查this

public class WebTexture { 
    private final String url; 
    private Texture texture; 
    private volatile byte[] textureBytes; 

    public WebTexture(String url, Texture tempTexture) { 
     this.url = url; 
     texture = tempTexture; 
     downloadTextureAsync(); 
    } 

    private void downloadTextureAsync() { 
     Utils.runInBackground(new Runnable() { 
      @Override 
      public void run() { 
       textureBytes = downloadTextureBytes(); 
      } 
     }); 
    } 

    private byte[] downloadTextureBytes() { 
     try { 
      return Utils.downloadData(url); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 

    public Texture getTexture() { 
     if (textureBytes != null) 
      processTextureBytes(); 
     return texture; 
    } 

    private void processTextureBytes() { 
     try { 
      Pixmap pixmap = new Pixmap(textureBytes, 0, textureBytes.length); 
      Texture gdxTexture = new Texture(pixmap); 
      gdxTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear); 
      texture = gdxTexture; 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } finally { 
      textureBytes = null; 
     } 
    } 
} 
+0

什麼是實用程序的導入? –