使用Picasso在后台线程上同步加载图像-不带.get() [英] Synchronous image loading on a background thread with Picasso - without .get()

查看:141
本文介绍了使用Picasso在后台线程上同步加载图像-不带.get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图组(其中包含毕加索加载的图像),可以在两个地方重复使用:

I have a custom viewgroup (that contains Picasso-loaded images) that can be reused in two places:

  1. 在应用程序中(在UI线程上)显示给用户
  2. 绘制到画布上并另存为.jpeg(在后台线程上)

我绘制到画布上的代码如下:

My code for drawing to the canvas looks like this:

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);

问题是在将视图绘制到画布上之前没有时间加载图像.我试图在此处尽可能避免耦合,所以我不希望不添加Picasso回调,因为进行绘制的类对绘制的视图一无所知.

The problem is that there is no time for the image to load before I draw the view to the canvas. I'm trying to avoid coupling as much as possible here so I'd prefer not to add a Picasso callback because the class that's doing the drawing doesn't know anything about the view that it's drawing.

我当前正在解决此问题,方法是将图像加载代码更改为.get()而不是.load(),然后使用imageView.setImageBitmap().不幸的是,这给视图增加了很多复杂性,我真的不喜欢它.

I'm currently working around the issue by changing the image loading code to .get() rather than .load() and then using imageView.setImageBitmap(). Unfortunately, this adds a ton of complexity to the view and I really don't like it.

我想做的是将一个选项传递给Picasso的RequestCreator,该请求应在当前线程上同步执行(如果是主线程,则引发异常).我想知道是否有太多的边缘案例无法直接在毕加索中建立支持?还是已经存在于API中,而我对此却一无所知?

What I'd like to do is pass an option to Picasso's RequestCreator that the request should be executed synchronously on the current thread (and throw an exception if it's the main thread). I wonder if this is too much of an edge case for support to be built directly into Picasso? Or is it already in the API and I'm oblivious to it?

推荐答案

这是我的解决方案:

/**
 * 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();
      }
    }
  }
}

这篇关于使用Picasso在后台线程上同步加载图像-不带.get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆