2014-12-01 31 views
2

我有一个自定义的ViewGroup(包含毕加索加载图像),可以在两个地方重复使用:同步图像加载 - 无需获得()

  1. 中显示给用户应用程序(UI线程)
  2. 吸引到画布并保存为JPEG格式(在后台线程)

我绘制在画布上的代码如下所示:

int measureSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); 
    view.measure(measureSpec, measureSpec); 
    Bitmap bitmap = 
     Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    view.draw(canvas); 

问题是,在我将画布绘制到视图之前没有时间加载图像。我试图尽量避免在这里耦合,所以我不想添加毕加索回调,因为正在执行绘图的类不知道它正在绘制的视图。

我目前通过将图像加载代码更改为.get()而不是​​,然后使用imageView.setImageBitmap()来解决此问题。不幸的是,这增加了很多复杂的观点,我真的不喜欢它。

我想要做的是将一个选项传递给毕加索的RequestCreator,该请求应该在当前线程上同步执行(并且如果它是主线程,则抛出异常)。我想知道这是否有太多的支持直接建立在毕加索的边缘情况?或者它已经在API中,我忘记了它?

+0

你可以尝试使用自定义毕加索改造公司招聘添加它作为你的请求的一部分,并运行你在那里 – Michael 2014-12-03 13:43:52

+0

感谢您的想法粘贴代码 - 图像是一个自定义的ViewGroup的只是一小部分,虽然,所以我不确定它会在这种情况下工作。 – 2014-12-03 16:26:41

+0

好的,很高兴你最终能够找到解决方案 – Michael 2014-12-04 09:08:52

回答

9

这里是我的解决方案:

/** 
* Loads the request into an imageview. 
* If called from a background thread, the request will be performed synchronously. 
* @param requestCreator A request creator 
* @param imageView The target imageview 
* @param callback a Picasso callback 
*/ 
public static void into(RequestCreator requestCreator, ImageView imageView, Callback callback) { 
    boolean mainThread = Looper.myLooper() == Looper.getMainLooper(); 
    if (mainThread) { 
    requestCreator.into(imageView, callback); 
    } else { 
    try { 
     Bitmap bitmap = requestCreator.get(); 
     imageView.setImageBitmap(bitmap); 
     if (callback != null) { 
     callback.onSuccess(); 
     } 
    } catch (IOException e) { 
     if (callback != null) { 
     callback.onError(); 
     } 
    } 
    } 
} 
+0

你能解释你如何使用它吗?你如何获得请求创建者?谢谢 – 2015-07-24 01:54:34

+1

'Picasso.load()'返回一个RequestCreator。您可以在RequestCreator上调用'.into()'来创建实际的图像加载请求。 – 2015-07-24 16:28:08

+0

你好,谢谢你的回答,这非常有帮助! 但是,你在回调中放了什么?我现在放空了。 – 2015-08-19 12:53:03

2

完美的答案雅各塔巴克

这里是添加少量如果您加载图像到Target处理该案件。我还没有找到一种方法来让图像的原点通过适当的LoadedFrom参数。

public static void into(RequestCreator requestCreator, Drawable placeHolder, Drawable errorDrawable, Target target) { 
     boolean mainThread = Looper.myLooper() == Looper.getMainLooper(); 
     if (mainThread) { 
      requestCreator.into(target); 
     } else { 
      try { 
       target.onBitmapFailed(placeHolder); 
       Bitmap bitmap = requestCreator.get(); 
       target.onBitmapLoaded(bitmap, Picasso.LoadedFrom.MEMORY); 
      } catch (IOException e) { 
       target.onBitmapFailed(errorDrawable); 
      } 
     } 
    }