简单说说我最常用的图片加载库 Picasso

对于一个需要展示很多图片或较多图片的App来说,一个好的图片加载框架是必不可少的。在我刚开始学习Android的时候,什么都想自己写,我以前做过一个看漫画的App,里面的图片加载,缓存等都是自己写的,但是效果并不理想,当时利用了LruCache来做图片的内存缓存,用DiskLruCache做磁盘缓存,加载图片根据Key先在内存中查询,如果没有就再去磁盘中查询,若果再没有在去网络上加载。虽然是个逻辑上非常清楚的事,但是要真的做好还是有一定的难度的。后来我认识到了Picasso,一个优雅、强大的图片加载框架,我使用它制作了许多的项目。虽然Picasso不是最强大的,现在有GlideFresco这些更强大的图片加载库,但在我眼里Picasso绝对是最优雅的,从它的API,设计方法,源码看,Picasso集轻量、实用于一身。

第一眼

认识它的第一眼肯定是它超级简短的使用方法,只需要一行代码,链式配置我们要加载的图片和一些加载配置和指定的加载Target,我们的图片就正确的加载并显示在了界面上,不可谓不优雅。

Picasso.with(context).load(url).into(imageView);复制代码

我们还可以很方便的配置各种加载选项,比如设置占位图,设置错误图,设置是否需要对图片进行变换,图片显示是否需要淡入效果,对图片的大小进行调整等常用的配置,这些都只需要一行代码就可以解决。

那么它是怎么做到的呢?作为一个开发者,首先要学会使用一个库,在学会了使用后,我们要去了解它,了解它的设计,了解它的实现,从中学习优秀的设计思想和编码技巧。

掌握一切的男人——Picasso(毕加索)

从使用上看,Picasso类无疑是掌握着一切的类,作为一个全局单例类,它掌握着各种配置(内存、磁盘、BitmapConfig、线程池等),提供各种简单有用的方法并隐藏了内部的各种实现,是我们使用上的超级核心类。Picasso的构造方法提供包级别的访问权限,我们不能直接new出来,但我们可以很简单的通过

Picasso.with(context)复制代码

来获取这个全局单例对象,来看一下with()方法

  public static Picasso with(@NonNull Context context) {
    if (context == null) {
      throw new IllegalArgumentException("context == null");
    }
    if (singleton == null) {
      synchronized (Picasso.class) {
        if (singleton == null) {
          singleton = new Builder(context).build();
        }
      }
    }
    return singleton;
  }复制代码

一个很经典的单例实现,内部使用建造者模式对Picasso对象进行构造。对于大多数简单的应用,只需要使用默认的配置就好了。但是对于一些应用,我们也可以通过Picasso.Builder来进行自定义的配置。我们可以根据类似下面的代码进行Picasso的配置

Picasso picasso = new Picasso.Builder(this)
        .loggingEnabled(true)
        .defaultBitmapConfig(Bitmap.Config.RGB_565)
        .build();
Picasso.setSingletonInstance(picasso);复制代码

由于Picasso是一个非常复杂的对象,根据不同的配置会产生不同的表现,这里通过建造者模式来构建对象很好的将构建和其表现分离。

RequestCreator

通过Picasso对象,我们可以load各种图片资源,这个资源可以字符路径、Uri、资源路径,文件等形式提供,之后Picasso会发挥一个RequestCreator对象,它可以根据我们需求以及图片资源生成相应的Request对象。之后Request会生成Action*对象,之后会分析这一系列的过程。由于RequestCreator的配置方法都返回自身,于是我们可以很方便的链式调用。

RequestCreator requestCreator = Picasso.with(this)
        .load("http://image.com")
        .config(Bitmap.Config.RGB_565)
        .centerInside()
        .fit()
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .noPlaceholder()
        .noFade();复制代码

into target——谈加载过程

requestCreator.into(new ImageView(this));复制代码

生成了RequestCreator后,我们可以调用其into()方法,该方法接受可以接收一个ImageView或者RemoteView或者Target对象,当然最后他们都会变为相应的Target对象来进行内部的图片加载。

接下来我们就来分析一下这被隐藏起来的加载过程。这里以最常用的into(imageView)进行分析。

public void into(ImageView target, Callback callback) {
  long started = System.nanoTime();
  checkMain();

  if (target == null) {
    throw new IllegalArgumentException("Target must not be null.");
  }

  if (!data.hasImage()) {
    picasso.cancelRequest(target);
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }
    return;
  }

  if (deferred) {
    if (data.hasSize()) {
      throw new IllegalStateException("Fit cannot be used with resize.");
    }
    int width = target.getWidth();
    int height = target.getHeight();
    if (width == 0 || height == 0) {
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      picasso.defer(target, new DeferredRequestCreator(this, target, callback));
      return;
    }
    data.resize(width, height);
  }

  Request request = createRequest(started);
  String requestKey = createKey(request);

  if (shouldReadFromMemoryCache(memoryPolicy)) {
    Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
    if (bitmap != null) {
      picasso.cancelRequest(target);
      setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
      if (picasso.loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
      }
      if (callback != null) {
        callback.onSuccess();
      }
      return;
    }
  }

  if (setPlaceholder) {
    setPlaceholder(target, getPlaceholderDrawable());
  }

  Action action =
      new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
          errorDrawable, requestKey, tag, callback, noFade);

  picasso.enqueueAndSubmit(action);
}复制代码

这个方法有点长,我们一点一点看,首先它检查了当前是否为主线程,若为主线程就抛出异常。

static void checkMain() {
  if (!isMain()) {
    throw new IllegalStateException("Method call should happen from the main thread.");
  }
}复制代码

之后判断我们给的图片的资源路径是否合法,如果不合法会取消生成请求,并直接显示占位图

if (!data.hasImage()) {
  picasso.cancelRequest(target);
  if (setPlaceholder) {
    setPlaceholder(target, getPlaceholderDrawable());
  }
  return;
}复制代码

若给的图片资源路径不为空,会检查一个defer字段的真假,只有当我们设置fit()时,defer才为true,因为fit()方法会让加载的图片以适应我们ImageView,所以只有当我们的ImageView laid out后才会去进行图片的获取并剪裁以适应。这里就不具体分析了,接下来往下看。

Request request = createRequest(started);

private Request createRequest(long started) {
    int id = nextId.getAndIncrement();

    Request request = data.build();
    request.id = id;
    request.started = started;

    boolean loggingEnabled = picasso.loggingEnabled;
    if (loggingEnabled) {
      log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
    }

    Request transformed = picasso.transformRequest(request);
    if (transformed != request) {
      // If the request was changed, copy over the id and timestamp from the original.
      transformed.id = id;
      transformed.started = started;

      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
      }
    }

    return transformed;
  }复制代码

接下来,终于生成了我们的Request对象,同Http请求的Request对象相同,这个Request对象包含了许多我们需要的信息已获得准确的回应。这里注意,我们的Request对象是可以通过RequestTransformer经过变换的,默认Picasso中内置的是一个什么也不变的RequestTransformer

默认的RequestTransformer

RequestTransformer IDENTITY = new RequestTransformer() {
  @Override public Request transformRequest(Request request) {
    return request;
  }
};复制代码

生成了Request对象后,这里来到了我们熟悉的一个步骤,就是检查内存中是否已经有图片的缓存了,当然它还更具我们设置的内存策略进行了是否需要进行内存检查。比如我们在查看大图的时候,一般会选择不让大图在内存缓存中存在,而是每次都去请求。

if (shouldReadFromMemoryCache(memoryPolicy)) {
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      if (bitmap != null) {
        picasso.cancelRequest(target);
        setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
        if (picasso.loggingEnabled) {
          log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
        }
        if (callback != null) {
          callback.onSuccess();
        }
        return;
      }
    }复制代码

找到的话就取消请求。否则会更具是否需要设置占位设置一下展位图,然后生成一个Action对象并使其加入队列发出。

if (setPlaceholder) {
  setPlaceholder(target, getPlaceholderDrawable());
}

Action action =
    new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
        errorDrawable, requestKey, tag, callback, noFade);

picasso.enqueueAndSubmit(action);复制代码

这个Action对象包含了我们的目标Target和请求数据Request以及相应的回调Callback等信息。

到这里我们还是没有真正的进行加载,最多只在内存中进行了缓存查询。

Go Action

通过上面的代码调用,我们了解到Picasso发出了一个Action,就像一个导演一样,说Action的时候就开始拍戏了,我们的Picasso在发出Action后就开始正式加载图片了。

Action最终会被Dispatcher给分发出去。

void submit(Action action) {
  dispatcher.dispatchSubmit(action);
}复制代码

Dispatcher随着Picasso的初始化而生成,正如其名,它负责所有Action的分发并将收到的结果也进行分发,分发给Picasso对象。我们来分析一下Dispatcher的工作过程。

Dispatcher内部是通过Handler进行工作的,这里插下嘴,Handler真是Android中超级强大的类,帮助我们轻松的实现线程之间的通信、切换,有许多有名的开源库都利用了Handler来实现功能,比如Google自家的响应式框架Agera,内部真是通过Handler实现的。所以我们要好好的掌握这个强大的类。

不多说了,我们继续看代码

void dispatchSubmit(Action action) {
  handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}复制代码

Dispatcher通过内部的Handler发送了一个消息,并将Action对象传递了出去,那么我们就要找到这个Handler对象的具体实现,根据收到的消息类型它做了哪些事情。

private static class DispatcherHandler extends Handler {
  private final Dispatcher dispatcher;

  public DispatcherHandler(Looper looper, Dispatcher dispatcher) {
    super(looper);
    this.dispatcher = dispatcher;
  }

  @Override public void handleMessage(final Message msg) {
    switch (msg.what) {
      case REQUEST_SUBMIT: {
        Action action = (Action) msg.obj;
        dispatcher.performSubmit(action);
        break;
      }
        ……
    }
  }
}复制代码

很容易找到了,就是执行了performSubmit(action)方法,继续来看下去,这里还没有具体的加载动作。

void performSubmit(Action action, boolean dismissFailed) {
  if (pausedTags.contains(action.getTag())) {
    pausedActions.put(action.getTarget(), action);
    if (action.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
          "because tag '" + action.getTag() + "' is paused");
    }
    return;
  }

  BitmapHunter hunter = hunterMap.get(action.getKey());
  if (hunter != null) {
    hunter.attach(action);
    return;
  }

  if (service.isShutdown()) {
    if (action.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
    }
    return;
  }

  hunter = forRequest(action.getPicasso(), this, cache, stats, action);
  hunter.future = service.submit(hunter);
  hunterMap.put(action.getKey(), hunter);
  if (dismissFailed) {
    failedActions.remove(action.getTarget());
  }

  if (action.getPicasso().loggingEnabled) {
    log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
  }
}复制代码

又是一段比较长的代码,但是还是很容易看懂的。主要就是生成了BitmapHunter对象,并将其发出。

hunter = forRequest(action.getPicasso(), this, cache, stats, action);
hunter.future = service.submit(hunter);复制代码

通过查看代码,我们知道这个service对象是一个ExecutorService,也就我们常用的线程池,这里Picasso默认使用的是PicassoExecutorService,在Dispatcher内部有一个监听网络变化广播的Receiver,Picasso会根据我们不同的网络变化(Wifi,4G,3G,2G)智能的切换线程池中该线程的数量,以帮助我们更好的节省流量。

既然线程池将BitmapHunter对象发出了,说明这个BitmapHunter对象一定是Runable的子类,从名字上来分析,我们也可以知道它肯定承担了Bitmap的获取生成。点进去一看源码,果然是这样的。哈哈。

线程池submit了一个Runable对象后,一定会调用其run()方法,我们就来看看它是不是加载了Bitmap吧~

@Override public void run() {
  try {
    updateThreadName(data);

    if (picasso.loggingEnabled) {
      log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
    }

    result = hunt();

    if (result == null) {
      dispatcher.dispatchFailed(this);
    } else {
      dispatcher.dispatchComplete(this);
    }
  } catch (Downloader.ResponseException e) {
    if (!e.localCacheOnly || e.responseCode != 504) {
      exception = e;
    }
    dispatcher.dispatchFailed(this);
  } catch (NetworkRequestHandler.ContentLengthException e) {
    exception = e;
    dispatcher.dispatchRetry(this);
  } catch (IOException e) {
    exception = e;
    dispatcher.dispatchRetry(this);
  } catch (OutOfMemoryError e) {
    StringWriter writer = new StringWriter();
    stats.createSnapshot().dump(new PrintWriter(writer));
    exception = new RuntimeException(writer.toString(), e);
    dispatcher.dispatchFailed(this);
  } catch (Exception e) {
    exception = e;
    dispatcher.dispatchFailed(this);
  } finally {
    Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
  }
}复制代码

代码虽长,核心只有hunt()一句,捕猎开始!BitmapHunter这个猎人开始狩猎Bitmap了。

Bitmap hunt() throws IOException {
  Bitmap bitmap = null;

  if (shouldReadFromMemoryCache(memoryPolicy)) {
    bitmap = cache.get(key);
    if (bitmap != null) {
      stats.dispatchCacheHit();
      loadedFrom = MEMORY;
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
      }
      return bitmap;
    }
  }

  data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
  RequestHandler.Result result = requestHandler.load(data, networkPolicy);
  if (result != null) {
    loadedFrom = result.getLoadedFrom();
    exifRotation = result.getExifOrientation();

    bitmap = result.getBitmap();

    // If there was no Bitmap then we need to decode it from the stream.
    if (bitmap == null) {
      InputStream is = result.getStream();
      try {
        bitmap = decodeStream(is, data);
      } finally {
        Utils.closeQuietly(is);
      }
    }
  }

  if (bitmap != null) {
    if (picasso.loggingEnabled) {
      log(OWNER_HUNTER, VERB_DECODED, data.logId());
    }
    stats.dispatchBitmapDecoded(bitmap);
    if (data.needsTransformation() || exifRotation != 0) {
      synchronized (DECODE_LOCK) {
        if (data.needsMatrixTransform() || exifRotation != 0) {
          bitmap = transformResult(data, bitmap, exifRotation);
          if (picasso.loggingEnabled) {
            log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());
          }
        }
        if (data.hasCustomTransformations()) {
          bitmap = applyCustomTransformations(data.transformations, bitmap);
          if (picasso.loggingEnabled) {
            log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from custom transformations");
          }
        }
      }
      if (bitmap != null) {
        stats.dispatchBitmapTransformed(bitmap);
      }
    }
  }

  return bitmap;
}复制代码

这个方法很长,最终返回我们所期望的Bitmap对象,说明这一个方法正是真正从各个渠道获取Bitmap对象的方法。我们看到,这里又进行了一次内存缓存的检查,避免两次请求相同图片的重复加载,没有的话,利用RequestHandler对象进行加载。RequestHandler是一个抽象类,load()方法抽象,因为根据不同图片的加载要执行不同的操作,比如从网络中获取,从resource中获取,从联系人中获取,从MediaStore获取等,这里运用了模板方法的模式,将一些方法将逻辑相同的方法公用,具体的加载细节子类决定,最终都返回Result对象。

根据不同的RequestHandler实例,我们可能可以直接获取一个Bitmap对象,也可能只获取一段流InputStream,比如网络加载图片时。如果结果以流的形式提供,那么Picasso会自动帮我们将流解析成Bitmap对象。之后根据我们之前通过RequestCreatorRequest的配置,决定是否对Bitmap对象进行变换,具体实现都大同小异,利用强大的Matrix,最后返回Bitmap。

之后我们再回到run()方法,假设这里我们成功获取到了Bitmap,那么是怎么传递的呢?这里还是利用了Dispatcher

if (result == null) {
  dispatcher.dispatchFailed(this);
} else {
  dispatcher.dispatchComplete(this);
}复制代码

和之前一样,Dispatcher内部通过Handler发送了一个特定的消息,然后执行。

void performComplete(BitmapHunter hunter) {
  if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
    cache.set(hunter.getKey(), hunter.getResult());
  }
  hunterMap.remove(hunter.getKey());
  batch(hunter);
  if (hunter.getPicasso().loggingEnabled) {
    log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
  }
}复制代码

上面就是它具体做的事,这里着重看batch()方法,相信这个方法一定是通过某种方式将猎人狩猎的Bitmap给上交给国家了。

private void batch(BitmapHunter hunter) {
  if (hunter.isCancelled()) {
    return;
  }
  batch.add(hunter);
  if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) {
    handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);
  }
}复制代码

咦?这里还是没有将Bitmap发出,但是通过handler发出了一个消息,恩恩,这都是套路了。这里有个设计很棒的地方,这里发送消息用了延时,为什么呢?为什么不马上发送呢?Picasso是将图片一批批的送出去的,每次发送的间隔为200ms,间隔不长也不短,这样有什么好处呢,好处就是如果我们看到一部分图片是一起加载出来的,而不是一张一张加载出来的。这个设计好贴心。前面根据网络情况决定线程池大小的做法也好贴心,Jake大大真是超棒!

找到了这个消息收到后具体执行的方法了

void performBatchComplete() {
  List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
  batch.clear();
  mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
  logBatch(copy);
}复制代码

这里就体现了Handler线程通信与切换的强大之处了,这里通过将一批Bitmap对象交给了处理主线程消息的Handler处理,这样我们获取到Bitmap并加载到ImageView上就是在主线程了操作的了,我们去看看这个Handler做了什么。这个Handler是在Dispatcher构造时传进来的,在Picasso类中定义。哈哈,正不亏是掌握一切权与利的对象,最苦最累的活让别人去做,自己做最风光体面的事。

static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
  @Override public void handleMessage(Message msg) {
    switch (msg.what) {
      case HUNTER_BATCH_COMPLETE: {
        @SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0, n = batch.size(); i < n; i++) {
          BitmapHunter hunter = batch.get(i);
          hunter.picasso.complete(hunter);
        }
        break;
      }
        ……
    }
};复制代码

不多说了,我们来看看代码,恩,很清楚的针对每个BitmapHunter执行了complete()方法,那就去看看喽。

void complete(BitmapHunter hunter) {
  Action single = hunter.getAction();
  List<Action> joined = hunter.getActions();

  boolean hasMultiple = joined != null && !joined.isEmpty();
  boolean shouldDeliver = single != null || hasMultiple;

  if (!shouldDeliver) {
    return;
  }

  Uri uri = hunter.getData().uri;
  Exception exception = hunter.getException();
  Bitmap result = hunter.getResult();
  LoadedFrom from = hunter.getLoadedFrom();

  if (single != null) {
    deliverAction(result, from, single);
  }

  if (hasMultiple) {
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0, n = joined.size(); i < n; i++) {
      Action join = joined.get(i);
      deliverAction(result, from, join);
    }
  }

  if (listener != null && exception != null) {
    listener.onImageLoadFailed(this, uri, exception);
  }
}复制代码

这个方法从BitmapHunter中获取Action对象,若这个Action成功完成,会执行Action的complete()方法,并将结果传入,很明显这是一个回调方法。Action也是一个抽象类,根据我们的Target不同会生成不同的Action对象,比如into(target)方法会生成TargetAction对象,into(imageView)会生成ImageViewAction对象,调用fetch()方法会产生FetchAction对象。这里由于我们是以将图片加载到ImageView中来分析的,所以我们只分析一下ImageViewAction的代码。

每个Action的子类要实现两个回调方法,一个error(),在图片加载失败时触发,一个complete(),在图片成功加载时调用。

@Override public void complete(Bitmap result, Picasso.LoadedFrom from) {
  if (result == null) {
    throw new AssertionError(
        String.format("Attempted to complete action with no result!\n%s", this));
  }

  ImageView target = this.target.get();
  if (target == null) {
    return;
  }

  Context context = picasso.context;
  boolean indicatorsEnabled = picasso.indicatorsEnabled;
  PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

  if (callback != null) {
    callback.onSuccess();
  }
}

@Override public void error() {
  ImageView target = this.target.get();
  if (target == null) {
    return;
  }
  Drawable placeholder = target.getDrawable();
  if (placeholder instanceof AnimationDrawable) {
    ((AnimationDrawable) placeholder).stop();
  }
  if (errorResId != 0) {
    target.setImageResource(errorResId);
  } else if (errorDrawable != null) {
    target.setImageDrawable(errorDrawable);
  }

  if (callback != null) {
    callback.onError();
  }
}复制代码

恩,很清楚的看到成功时就正确显示图片,失败时则根据是否设置了错误图来选择是否加载错误图。这里用到了一个PicassoDrawable的类,这个类继承自BitmapDrawable类,通过它,可以很方便的实现淡入淡出效果。

总结

到这里,我们分析完了一次成功的Picasso图片加载过程,当然我们不可能每次都成功,也会发生各种错误,或者我们暂停了加载又继续加载等,这些Picasso都作出了不同的处理,线程之间通过Handler进行通信。这里就不一一详述了。相信大家自己会去看的。

不得不说,Picasso真是一个优雅的图片加载库,用极少的代码完成了了不起的事,从API的设计到代码的编写,无不体现了作者的深思熟虑和贴心,运用多用设计模式巧妙地提供极其简单的调用接口,隐藏背后复杂的实现。通过对Picasso的使用与源码分析,我学到了很多,希望我以后也可以设计出这么优雅实用的库或框架。

天道酬勤,我要加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值