2016-10-26 64 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()]); 
    } 
} 

希望有所帮助。