2016-10-26 62 views
2

我想從我的String []鏈接獲取位圖[]。但是這不符合我的要求。我有這樣的方法:Android從畢加索獲取圖像到位圖陣列

private Bitmap[] getBitmaps(String[] images){ 
    ArrayList<Bitmap> temp = new ArrayList<>(); 
    for(int i = 0; i < images.length; i++){ 
     ImageView img = new ImageView(getContext()); 
     FrameLayout.LayoutParams x = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
     img.setLayoutParams(x); 
     Picasso.with(getContext()).load(MainPostAdapter.USER_URL+images[i]+".png").into(img, new Callback() { 
      @Override 
      public void onSuccess() { 
       temp.add(BitmapRes.drawableToBitmap(img.getDrawable())); 
       movableBackgroundContainer.removeView(img); 
      } 

      @Override 
      public void onError() { 

      } 
     }); 
     movableBackgroundContainer.addView(img); 
    } 
    return temp.toArray(new Bitmap[temp.size()]); 
} 

問題是,我得到一個空數組,因爲它的onSuccess功能後增加了位圖到列表中。我現在如何等待,直到所有onSuccess添加位圖,然後返回?

回答

4

畢加索的get()功能可以滿足您的要求。它下載一個位圖而不是將圖像加載到ImageView中。請注意,畢加索的get()方法不能在主線程中調用。我的示例使用AsyncTask在單獨的線程上下載圖像。

String[] images = new String[] {"http://path.to.image1.jpg", "http://path.to.image2.jpg"}; 
    new AsyncTask<String[], Void, List<Bitmap>>() { 
     @Override 
     protected List<Bitmap> doInBackground(String[]... params) { 
      try { 
       List<Bitmap> bitmaps = new ArrayList<Bitmap>(); 
       for (int i = 0; i < params[0].length; ++i) { 
        bitmaps.add(Picasso.with(getActivity()).load(params[0][i]).get()); 
       } 
       return bitmaps; 
      } catch (IOException e) { 
       return null; 
      } 
     } 

     @Override 
     public void onPostExecute(List<Bitmap> bitmaps) { 
      if (bitmaps != null) { 
       // Do stuff with your loaded bitmaps 
      } 
     } 
    }.execute(images); 
1

您可以每次成功時增加一個整數,直到整數等於images.lengh()。你可以用循環來檢查它。並且在循環中返回一個if子句。

例如

int currentSuccess = 0; 

在循環:

 @Override 
      public void onSuccess() { 
       temp.add(BitmapRes.drawableToBitmap(img.getDrawable())); 
       movableBackgroundContainer.removeView(img); 
       currentSuccess++; 
      } 

而對於回報:

while(true){ 
    if(currentSuccess == images.length){ 
     return temp.toArray(new Bitmap[temp.size()]); 
    } 
} 

希望有所幫助。