| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
z_jide
7年前发布

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

   <h2>简单说说我最常用的图片加载库Picasso</h2>    <p>对于一个需要展示很多图片或较多图片的App来说,一个好的图片加载框架是必不可少的。在我刚开始学习Android的时候,什么都想自己写,我以前做过一个看漫画的App,里面的图片加载,缓存等都是自己写的,但是效果并不理想,当时利用了 LruCache 来做图片的内存缓存,用 DiskLruCache 做磁盘缓存,加载图片根据Key先在内存中查询,如果没有就再去磁盘中查询,若果再没有在去网络上加载。虽然是个逻辑上非常清楚的事,但是要真的做好还是有一定的难度的。后来我认识到了 <strong>Picasso</strong> ,一个优雅、强大的图片加载框架,我使用它制作了许多的项目。虽然 <strong>Picasso</strong> 不是最强大的,现在有 <strong>Glide</strong> 、 <strong>Fresco</strong> 这些更强大的图片加载库,但在我眼里 <strong>Picasso</strong> 绝对是最优雅的,从它的API,设计方法,源码看, <strong>Picasso</strong> 集轻量、实用于一身。</p>    <h3>第一眼</h3>    <p>认识它的第一眼肯定是它超级简短的使用方法,只需要一行代码,链式配置我们要加载的图片和一些加载配置和指定的加载Target,我们的图片就正确的加载并显示在了界面上,不可谓不优雅。</p>    <pre>  <code class="language-java">Picasso.with(context).load(url).into(imageView);</code></pre>    <p>我们还可以很方便的配置各种加载选项,比如设置占位图,设置错误图,设置是否需要对图片进行变换,图片显示是否需要淡入效果,对图片的大小进行调整等常用的配置,这些都只需要一行代码就可以解决。</p>    <p>那么它是怎么做到的呢?作为一个开发者,首先要学会使用一个库,在学会了使用后,我们要去了解它,了解它的设计,了解它的实现,从中学习优秀的设计思想和编码技巧。</p>    <h3>掌握一切的男人——Picasso(毕加索)</h3>    <p>从使用上看, Picasso 类无疑是掌握着一切的类,作为一个全局单例类,它掌握着各种配置(内存、磁盘、BitmapConfig、线程池等),提供各种简单有用的方法并隐藏了内部的各种实现,是我们使用上的超级核心类。Picasso的构造方法提供包级别的访问权限,我们不能直接new出来,但我们可以很简单的通过</p>    <pre>  <code class="language-java">Picasso.with(context)</code></pre>    <p>来获取这个全局单例对象,来看一下 with() 方法</p>    <pre>  <code class="language-java">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;    }</code></pre>    <p>一个很经典的单例实现,内部使用建造者模式对 <strong>Picasso</strong> 对象进行构造。对于大多数简单的应用,只需要使用默认的配置就好了。但是对于一些应用,我们也可以通过 <strong>Picasso.Builder</strong> 来进行自定义的配置。我们可以根据类似下面的代码进行Picasso的配置</p>    <pre>  <code class="language-java">Picasso picasso = new Picasso.Builder(this)          .loggingEnabled(true)          .defaultBitmapConfig(Bitmap.Config.RGB_565)          .build();  Picasso.setSingletonInstance(picasso);</code></pre>    <p>由于Picasso是一个非常复杂的对象,根据不同的配置会产生不同的表现,这里通过建造者模式来构建对象很好的将构建和其表现分离。</p>    <h3>RequestCreator</h3>    <p>通过Picasso对象,我们可以load各种图片资源,这个资源可以字符路径、Uri、资源路径,文件等形式提供,之后Picasso会发挥一个 RequestCreator 对象,它可以根据我们需求以及图片资源生成相应的 Request 对象。之后 Request 会生成 Action* 对象,之后会分析这一系列的过程。由于 RequestCreator 的配置方法都返回自身,于是我们可以很方便的链式调用。</p>    <pre>  <code class="language-java">RequestCreator requestCreator = Picasso.with(this)          .load("http://image.com")          .config(Bitmap.Config.RGB_565)          .centerInside()          .fit()          .memoryPolicy(MemoryPolicy.NO_CACHE)          .noPlaceholder()          .noFade();</code></pre>    <h3>into target——谈加载过程</h3>    <pre>  <code class="language-java">requestCreator.into(new ImageView(this));</code></pre>    <p>生成了 RequestCreator 后,我们可以调用其into()方法,该方法接受可以接收一个 ImageView 或者 RemoteView 或者 Target 对象,当然最后他们都会变为相应的 Target 对象来进行内部的图片加载。</p>    <p>接下来我们就来分析一下这被隐藏起来的加载过程。这里以最常用的 into(imageView) 进行分析。</p>    <pre>  <code class="language-java">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);  }</code></pre>    <p>这个方法有点长,我们一点一点看,首先它检查了当前是否为主线程,若为主线程就抛出异常。</p>    <pre>  <code class="language-java">static void checkMain() {    if (!isMain()) {      throw new IllegalStateException("Method call should happen from the main thread.");    }  }</code></pre>    <p>之后判断我们给的图片的资源路径是否合法,如果不合法会取消生成请求,并直接显示占位图</p>    <pre>  <code class="language-java">if (!data.hasImage()) {    picasso.cancelRequest(target);    if (setPlaceholder) {      setPlaceholder(target, getPlaceholderDrawable());    }    return;  }</code></pre>    <p>若给的图片资源路径不为空,会检查一个 defer 字段的真假,只有当我们设置 fit() 时,defer才为 true ,因为 fit() 方法会让加载的图片以适应我们 ImageView ,所以只有当我们的 ImageView laid out后才会去进行图片的获取并剪裁以适应。这里就不具体分析了,接下来往下看。</p>    <pre>  <code class="language-java">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;    }</code></pre>    <p>接下来,终于生成了我们的 Request 对象,同Http请求的Request对象相同,这个 Request 对象包含了许多我们需要的信息已获得准确的回应。这里注意,我们的 Request 对象是可以通过 RequestTransformer 经过变换的,默认Picasso中内置的是一个什么也不变的 RequestTransformer 。</p>    <p>默认的 RequestTransformer</p>    <pre>  <code class="language-java">RequestTransformer IDENTITY = new RequestTransformer() {    @Override public Request transformRequest(Request request) {      return request;    }  };</code></pre>    <p>生成了 Request 对象后,这里来到了我们熟悉的一个步骤,就是检查内存中是否已经有图片的缓存了,当然它还更具我们设置的内存策略进行了是否需要进行内存检查。比如我们在查看大图的时候,一般会选择不让大图在内存缓存中存在,而是每次都去请求。</p>    <pre>  <code class="language-java">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;        }      }</code></pre>    <p>找到的话就取消请求。否则会更具是否需要设置占位设置一下展位图,然后生成一个 Action 对象并使其加入队列发出。</p>    <pre>  <code class="language-java">if (setPlaceholder) {    setPlaceholder(target, getPlaceholderDrawable());  }    Action action =      new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,          errorDrawable, requestKey, tag, callback, noFade);    picasso.enqueueAndSubmit(action);</code></pre>    <p>这个 Action 对象包含了我们的目标 Target 和请求数据 Request 以及相应的回调Callback等信息。</p>    <p>到这里我们还是没有真正的进行加载,最多只在内存中进行了缓存查询。</p>    <h3>Go Action</h3>    <p>通过上面的代码调用,我们了解到Picasso发出了一个 Action ,就像一个导演一样,说Action的时候就开始拍戏了,我们的Picasso在发出 Action 后就开始正式加载图片了。</p>    <p>Action 最终会被 Dispatcher 给分发出去。</p>    <pre>  <code class="language-java">void submit(Action action) {    dispatcher.dispatchSubmit(action);  }</code></pre>    <p>Dispatcher 随着Picasso的初始化而生成,正如其名,它负责所有Action的分发并将收到的结果也进行分发,分发给Picasso对象。我们来分析一下Dispatcher的工作过程。</p>    <p>Dispatcher 内部是通过 Handler 进行工作的,这里插下嘴,Handler真是Android中超级强大的类,帮助我们轻松的实现线程之间的通信、切换,有许多有名的开源库都利用了 Handler 来实现功能,比如Google自家的响应式框架 Agera ,内部真是通过 Handler 实现的。所以我们要好好的掌握这个强大的类。</p>    <p>不多说了,我们继续看代码</p>    <pre>  <code class="language-java">void dispatchSubmit(Action action) {    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));  }</code></pre>    <p>Dispatcher 通过内部的 Handler 发送了一个消息,并将 Action 对象传递了出去,那么我们就要找到这个 Handler 对象的具体实现,根据收到的消息类型它做了哪些事情。</p>    <pre>  <code class="language-java">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;        }          ……      }    }  }</code></pre>    <p>很容易找到了,就是执行了 performSubmit(action) 方法,继续来看下去,这里还没有具体的加载动作。</p>    <pre>  <code class="language-java">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());    }  }</code></pre>    <p>又是一段比较长的代码,但是还是很容易看懂的。主要就是生成了 BitmapHunter 对象,并将其发出。</p>    <pre>  <code class="language-java">hunter = forRequest(action.getPicasso(), this, cache, stats, action);  hunter.future = service.submit(hunter);</code></pre>    <p>通过查看代码,我们知道这个 service 对象是一个 ExecutorService ,也就我们常用的线程池,这里Picasso默认使用的是 PicassoExecutorService ,在Dispatcher内部有一个监听网络变化广播的Receiver,Picasso会根据我们不同的网络变化(Wifi,4G,3G,2G)智能的切换线程池中该线程的数量,以帮助我们更好的节省流量。</p>    <p>既然线程池将 BitmapHunter 对象发出了,说明这个 BitmapHunter 对象一定是 Runable 的子类,从名字上来分析,我们也可以知道它肯定承担了Bitmap的获取生成。点进去一看源码,果然是这样的。哈哈。</p>    <p>线程池submit了一个 Runable 对象后,一定会调用其 run() 方法,我们就来看看它是不是加载了 Bitmap 吧~</p>    <pre>  <code class="language-java">@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);    }  }</code></pre>    <p>代码虽长,核心只有 hunt() 一句,捕猎开始! BitmapHunter 这个猎人开始狩猎 Bitmap 了。</p>    <pre>  <code class="language-java">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;  }</code></pre>    <p>这个方法很长,最终返回我们所期望的 Bitmap 对象,说明这一个方法正是真正从各个渠道获取 Bitmap 对象的方法。我们看到,这里又进行了一次内存缓存的检查,避免两次请求相同图片的重复加载,没有的话,利用 RequestHandler 对象进行加载。 RequestHandler 是一个抽象类, load() 方法抽象,因为根据不同图片的加载要执行不同的操作,比如从网络中获取,从resource中获取,从联系人中获取,从MediaStore获取等,这里运用了模板方法的模式,将一些方法将逻辑相同的方法公用,具体的加载细节子类决定,最终都返回 Result 对象。</p>    <p>根据不同的 RequestHandler 实例,我们可能可以直接获取一个Bitmap对象,也可能只获取一段流InputStream,比如网络加载图片时。如果结果以流的形式提供,那么Picasso会自动帮我们将流解析成Bitmap对象。之后根据我们之前通过 RequestCreator 对 Request 的配置,决定是否对Bitmap对象进行变换,具体实现都大同小异,利用强大的Matrix,最后返回Bitmap。</p>    <p>之后我们再回到 run() 方法,假设这里我们成功获取到了 Bitmap ,那么是怎么传递的呢?这里还是利用了 Dispatcher</p>    <pre>  <code class="language-java">if (result == null) {    dispatcher.dispatchFailed(this);  } else {    dispatcher.dispatchComplete(this);  }</code></pre>    <p>和之前一样, Dispatcher 内部通过Handler发送了一个特定的消息,然后执行。</p>    <pre>  <code class="language-java">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");    }  }</code></pre>    <p>上面就是它具体做的事,这里着重看 batch() 方法,相信这个方法一定是通过某种方式将猎人狩猎的Bitmap给上交给国家了。</p>    <pre>  <code class="language-java">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);    }  }</code></pre>    <p>咦?这里还是没有将 Bitmap 发出,但是通过handler发出了一个消息,恩恩,这都是套路了。这里有个设计很棒的地方,这里发送消息用了延时,为什么呢?为什么不马上发送呢?Picasso是将图片一批批的送出去的,每次发送的间隔为200ms,间隔不长也不短,这样有什么好处呢,好处就是如果我们看到一部分图片是一起加载出来的,而不是一张一张加载出来的。这个设计好贴心。前面根据网络情况决定线程池大小的做法也好贴心,Jake大大真是超棒!</p>    <p>找到了这个消息收到后具体执行的方法了</p>    <pre>  <code class="language-java">void performBatchComplete() {    List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);    batch.clear();    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));    logBatch(copy);  }</code></pre>    <p>这里就体现了Handler线程通信与切换的强大之处了,这里通过将一批Bitmap对象交给了处理主线程消息的Handler处理,这样我们获取到Bitmap并加载到ImageView上就是在主线程了操作的了,我们去看看这个Handler做了什么。这个Handler是在Dispatcher构造时传进来的,在Picasso类中定义。哈哈,正不亏是掌握一切权与利的对象,最苦最累的活让别人去做,自己做最风光体面的事。</p>    <pre>  <code class="language-java">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;        }          ……      }  };</code></pre>    <p>不多说了,我们来看看代码,恩,很清楚的针对每个BitmapHunter执行了 complete() 方法,那就去看看喽。</p>    <pre>  <code class="language-java">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);    }  }</code></pre>    <p>这个方法从 BitmapHunter 中获取 Action 对象,若这个 Action 成功完成,会执行Action的 complete() 方法,并将结果传入,很明显这是一个回调方法。Action也是一个抽象类,根据我们的 Target 不同会生成不同的Action对象,比如 into(target) 方法会生成 TargetAction 对象, into(imageView) 会生成 ImageViewAction 对象,调用fetch()方法会产生 FetchAction 对象。这里由于我们是以将图片加载到ImageView中来分析的,所以我们只分析一下 ImageViewAction 的代码。</p>    <p>每个 Action 的子类要实现两个回调方法,一个 error() ,在图片加载失败时触发,一个 complete() ,在图片成功加载时调用。</p>    <pre>  <code class="language-java">@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();    }  }</code></pre>    <p>恩,很清楚的看到成功时就正确显示图片,失败时则根据是否设置了错误图来选择是否加载错误图。这里用到了一个 PicassoDrawable 的类,这个类继承自 BitmapDrawable 类,通过它,可以很方便的实现淡入淡出效果。</p>    <h3>总结</h3>    <p>到这里,我们分析完了一次成功的Picasso图片加载过程,当然我们不可能每次都成功,也会发生各种错误,或者我们暂停了加载又继续加载等,这些Picasso都作出了不同的处理,线程之间通过Handler进行通信。这里就不一一详述了。相信大家自己会去看的。</p>    <p>不得不说,Picasso真是一个优雅的图片加载库,用极少的代码完成了了不起的事,从API的设计到代码的编写,无不体现了作者的深思熟虑和贴心,运用多用设计模式巧妙地提供极其简单的调用接口,隐藏背后复杂的实现。通过对Picasso的使用与源码分析,我学到了很多,希望我以后也可以设计出这么优雅实用的库或框架。</p>    <p>天道酬勤,我要加油!</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/1b610c29e596</p>    <p> </p>    
 本文由用户 z_jide 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1482375677093.html
Bitmap 安卓开发 Android开发 移动开发