第 4 章 第三方类库

2018-02-24 15:57 更新

本文内容包括:

自定义网络加载

Image pipeline 默认使用 HttpURLConnection 。应用可以根据自己需求使用不同的网络库。

OkHttp

OkHttp 是一个流行的开源网络请求库。Imagepipeline有一个使用OkHttp替换掉了Android默认的网络请求的补充。

如果需要使用OkHttp,不要使用这个下载页面的gradle依赖配置,应该使用下面的依赖配置

dependencies {
  // your project's other dependencies
  compile: "com.facebook.fresco:drawee:0.1.0+"
  compile: "com.facebook.fresco:imagepipeline-okhttp:0.1.0+"
}

配置Imagepipeline这时也有一些不同,不再使用ImagePipelineConfig.newBuilder,而是使用OkHttpImagePipelineConfigFactory:

Context context;
OkHttpClient okHttpClient; // build on your own
ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
    .newBuilder(context, okHttpClient)
    . // other setters
    . // setNetworkFetchProducer is already called for you
    .build();
Fresco.initialize(context, config);

使用自定的网络层

For complete control on how the networking layer should behave, you can provide one for your app. You must subclass 为了完全控制网络层的行为,你可以自定义网络层。继承 NetworkFetchProducer , 这个类包含了网络通信。

你也可以选择性地继承 NfpRequestState , 这个类是请求时的数据结构描述。

默认的 HttpURLConnection 可以作为一个参考.

在配置 Image pipeline 时,把producer传递给Image pipeline。

ImagePipelineConfig config = ImagePipelineConfig.newBuilder()
  .setNetworkFetchProducer(myNetworkFetchProducer);
  . // other setters
  .build();
Fresco.initialize(context, config);

使用其他的Image Loader

Drawee 并不是吊死在特定的一种图片加载机制上,它同样适用于其他 image loader。

不过有一些特性,只有Fresco image pipeline才有。前面的提到的需要使用 ImageRequest 和配置 imagepipeline的特性,使用其他image loader时都有可能不起作用。

Drawee 和 Volley ImageLoader配合使用

我们有一个Drawee使用Volley的 ImageLoader 的补充实现。

我们仅仅对那些已经深度使用Volley ImageLoader的应用推荐这个组合。

同样地,如要使用,使用下面的依赖,而不是下载页面给出的依赖:

dependencies {
  // your project's other dependencies
  compile: "com.facebook.fresco:drawee-volley:0.1.0+"
}

初始化Volley ImageLoader

这时,不需要再调用Fresco.initialize了,需要的是初始化Volley。

Context context;
ImageLoader imageLoader; // build yourself
VolleyDraweeControllerBuilderSupplier mControllerBuilderSupplier
    = new VolleyDraweeControllerBuilderSupplier(context, imageLoader);
SimpleDraweeView.initialize(mControllerBuilderSupplier);

不要让 VolleyDraweeControllerBuilderSupplier离开作用域,你需要它来创建DraweeController,除非你只使用SimpleDraweeView.setImageURI

DraweeControllers 和 Volley ImageLoader 配合使用

不是调用Fresco.newControllerBuilder, 而是:

VolleyController controller = mControllerBuilderSupplier
    .newControllerBuilder()
    . // setters
    .build();
mSimpleDraweeView.setController(controller);

Drawee 和其他Image Loader 配合使用

依照源码 作为例子,其他Image Loader也是可以和Drawee配合使用的,但是没有我们还没有Drawee和其他Image loader的配合使用的补充实现。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号