Fresco源码解析 - 创建一个ImagePipeline(一)

Fresco源码解析 - 初始化过程分析章节中,我们分析了Fresco的初始化过程,两个initialize方法中都用到了 ImagePipelineFactory类。

ImagePipelineFactory.initialize(context);会创建一个所有参数都使用默认值的ImagePipelineConfig来初始化ImagePipeline

ImagePipelineFactory.initialize(imagePipelineConfig)会首先用 imagePipelineConfig创建一个ImagePipelineFactory的实例 - sInstance

sInstance = new ImagePipelineFactory(imagePipelineConfig);

然后,初始化Drawee时,在PipelineDraweeControllerBuilderSupplier的构造方法中通过 ImagePipelineFactory.getInstance()获取这个实例。

Fresco.java

private static void initializeDrawee(Context context) {
  sDraweeControllerBuilderSupplier = new PipelineDraweeControllerBuilderSupplier(context);
  SimpleDraweeView.initialize(sDraweeControllerBuilderSupplier);
}

PipelineDraweeControllerBuilderSupplier.java

public PipelineDraweeControllerBuilderSupplier(Context context) {
  this(context, ImagePipelineFactory.getInstance());
}

public PipelineDraweeControllerBuilderSupplier(
    Context context,
    ImagePipelineFactory imagePipelineFactory) {
  this(context, imagePipelineFactory, null);
}

PipelineDraweeControllerBuilderSupplier还有一个构造方法,就是 this(context, imagePipelineFactory, null)调用的构造方法。

public PipelineDraweeControllerBuilderSupplier(
    Context context,
    ImagePipelineFactory imagePipelineFactory,
    Set<ControllerListener> boundControllerListeners) {
  mContext = context;
  mImagePipeline = imagePipelineFactory.getImagePipeline();
  mPipelineDraweeControllerFactory = new PipelineDraweeControllerFactory(
      context.getResources(),
      DeferredReleaser.getInstance(),
      imagePipelineFactory.getAnimatedDrawableFactory(),
      UiThreadImmediateExecutorService.getInstance());
  mBoundControllerListeners = boundControllerListeners;
}

其中,mImagePipeline = imagePipelineFactory.getImagePipeline()用于获取ImagePipeline的实例。

ImagePipelineFactory.java

public ImagePipeline getImagePipeline() {
  if (mImagePipeline == null) {
    mImagePipeline =
        new ImagePipeline(
            getProducerSequenceFactory(),
            mConfig.getRequestListeners(),
            mConfig.getIsPrefetchEnabledSupplier(),
            getBitmapMemoryCache(),
            getEncodedMemoryCache(),
            mConfig.getCacheKeyFactory());
  }
  return mImagePipeline;
}

可以看出mImagePipeline是一个单例,构造ImagePipeline时用到的mConfig就是本片最开始讲到的 ImagePipelineConfig imagePipelineConfig

经过这个过程,一个ImagePipeline就被创建好了,下面我们具体解析一下ImagePipeline的每个参数。



因为ImagePipelineFactoryImagePipelineConfig来创建一个ImagePipeline,我们首先分析一下ImagePipelineConfig的源码。

public class ImagePipelineConfig {
  private final Supplier<MemoryCacheParams> mBitmapMemoryCacheParamsSupplier;
  private final CacheKeyFactory mCacheKeyFactory;
  private final Context mContext;
  private final Supplier<MemoryCacheParams> mEncodedMemoryCacheParamsSupplier;
  private final ExecutorSupplier mExecutorSupplier;
  private final ImageCacheStatsTracker mImageCacheStatsTracker;
  private final AnimatedDrawableUtil mAnimatedDrawableUtil;
  private final AnimatedImageFactory mAnimatedImageFactory;
  private final ImageDecoder mImageDecoder;
  private final Supplier<Boolean> mIsPrefetchEnabledSupplier;
  private final DiskCacheConfig mMainDiskCacheConfig;
  private final MemoryTrimmableRegistry mMemoryTrimmableRegistry;
  private final NetworkFetcher mNetworkFetcher;
  private final PoolFactory mPoolFactory;
  private final ProgressiveJpegConfig mProgressiveJpegConfig;
  private final Set<RequestListener> mRequestListeners;
  private final boolean mResizeAndRotateEnabledForNetwork;
  private final DiskCacheConfig mSmallImageDiskCacheConfig;
  private final PlatformBitmapFactory mPlatformBitmapFactory;

  // other methods
}

上图可以看出,获取图像的第一站是Memeory Cache,然后是Disk Cache,最后是Network,而MemoryDisk都是缓存在本地的数据,MemoryCacheParams就用于表示它们的缓存策略。

MemoryCacheParams.java

  /**
   * Pass arguments to control the cache‘s behavior in the constructor.
   *
   * @param maxCacheSize The maximum size of the cache, in bytes.
   * @param maxCacheEntries The maximum number of items that can live in the cache.
   * @param maxEvictionQueueSize The eviction queue is an area of memory that stores items ready
   *                             for eviction but have not yet been deleted. This is the maximum
   *                             size of that queue in bytes.
   * @param maxEvictionQueueEntries The maximum number of entries in the eviction queue.
   * @param maxCacheEntrySize The maximum size of a single cache entry.
   */
  public MemoryCacheParams(
      int maxCacheSize,
      int maxCacheEntries,
      int maxEvictionQueueSize,
      int maxEvictionQueueEntries,
      int maxCacheEntrySize) {
    this.maxCacheSize = maxCacheSize;
    this.maxCacheEntries = maxCacheEntries;
    this.maxEvictionQueueSize = maxEvictionQueueSize;
    this.maxEvictionQueueEntries = maxEvictionQueueEntries;
    this.maxCacheEntrySize = maxCacheEntrySize;
  }

关于每个参数的作用,注释已经写得很清楚,不再赘述。



CacheKeyFactory会为ImageRequest创建一个索引 - CacheKey

/**
 * Factory methods for creating cache keys for the pipeline.
 */
public interface CacheKeyFactory {

  /**
   * @return {@link CacheKey} for doing bitmap cache lookups in the pipeline.
   */
  public CacheKey getBitmapCacheKey(ImageRequest request);

  /**
   * @return {@link CacheKey} for doing encoded image lookups in the pipeline.
   */
  public CacheKey getEncodedCacheKey(ImageRequest request);

  /**
   * @return a {@link String} that unambiguously indicates the source of the image.
   */
  public Uri getCacheKeySourceUri(Uri sourceUri);
}


ExecutorSupplier会根据ImagePipeline的使用场景获取不同的Executor

public interface ExecutorSupplier {

  /** Executor used to do all disk reads, whether for disk cache or local files. */
  Executor forLocalStorageRead();

  /** Executor used to do all disk writes, whether for disk cache or local files. */
  Executor forLocalStorageWrite();

  /** Executor used for all decodes. */
  Executor forDecode();

  /** Executor used for all image transformations, such as transcoding, resizing, and rotating. */
  Executor forTransform();

  /** Executor used for background operations, such as postprocessing. */
  Executor forBackground();
}


ImageCacheStatsTracker 作为 Cache 埋点工具,可以统计Cache的各种操作数据。

public interface ImageCacheStatsTracker {

  /** Called whenever decoded images are put into the bitmap cache. */
  public void onBitmapCachePut();

  /** Called on a bitmap cache hit. */
  public void onBitmapCacheHit();

  /** Called on a bitmap cache miss. */
  public void onBitmapCacheMiss();

  /** Called whenever encoded images are put into the encoded memory cache. */
  public void onMemoryCachePut();

  /** Called on an encoded memory cache hit. */
  public void onMemoryCacheHit();

  /** Called on an encoded memory cache hit. */
  public void onMemoryCacheMiss();

  /**
   * Called on an staging area hit.
   *
   * <p>The staging area stores encoded images. It gets the images before they are written
   * to disk cache.
   */
  public void onStagingAreaHit();

  /** Called on a staging area miss hit. */
  public void onStagingAreaMiss();

  /** Called on a disk cache hit. */
  public void onDiskCacheHit();

  /** Called on a disk cache miss. */
  public void onDiskCacheMiss();

  /** Called if an exception is thrown on a disk cache read. */
  public void onDiskCacheGetFail();

  /**
   * Registers a bitmap cache with this tracker.
   *
   * <p>Use this method if you need access to the cache itself to compile your stats.
   */
  public void registerBitmapMemoryCache(CountingMemoryCache<?, ?> bitmapMemoryCache);

  /**
   * Registers an encoded memory cache with this tracker.
   *
   * <p>Use this method if you need access to the cache itself to compile your stats.
   */
  public void registerEncodedMemoryCache(CountingMemoryCache<?, ?> encodedMemoryCache);
}

剩下的几个参数与Drawable关联比较大,我们下一篇再分析。

めっちゃ眠くて、寝て行っちゃうから、じゃねー。

时间: 2024-10-05 10:08:00

Fresco源码解析 - 创建一个ImagePipeline(一)的相关文章

Fresco源码解析 - 初始化过程分析

使用Fresco之前,一定先要进行初始化,一般初始化的工作会在Application.onCreate()完成,当然也可以在使用Drawee之前完成. Fresco本身提供了两种初始化方式,一种是使用使用默认配置初始化,另一种是使用用户自定义配置. 如下代码是Fresco提供的两个初始化方法.第一个只需要提供一个Context参数,第二个还需要提供 ImagePipeline 的配置实例 - ImagePipelineConfig. /** Initializes Fresco with the

Fresco源码解析 - 本地编译

第一次写专栏,如有表述不好或者理解错误的地方,请各位读者不吝赐教,本人一定虚心接受并第一时间改正. 作为专题第一篇,先从最简单的开始,顺便找找感觉. Fresco 是 facebook 在今年的 F8 大会上宣布开源的一个用于加载图片的库,它不仅支持多种图片文件格式,而且由于使用了pinned purgeables 技术,使得大图加载过程中产生OOM的概率大大降低,对开发者来说绝对是一件喜大普奔的事情,对于像天猫HD这样需要加载大量图片的APP来说也绝对是个福音. 下载代码 首先把源码从 Git

Fresco源码解析 - DraweeView

DraweeView 是Fresco的三大组件(Hierarchy.Controller.View) 之一,作为MVC模式中的 View,主要负责显示由 Hierarchy 提供的数据(placeholder.actual image.progress drawable等),Controller 作为幕后,负责获取数据. 继承体系 DraweeView 并不是是一个简单的自定义View,它必须要提供与 Hierarchy 和 Controller 交互的接口,DraweeView 的继承关系如下

Fresco源码解析 - DataSource怎样存储数据

datasource是一个独立的 package,与FB导入的guava包都在同一个工程内 - fbcore. datasource的类关系比较简单,一张类图基本就可以描述清楚它们间的关系. DataSource 是一个 interface, 功能与JDK中的Future类似,但是相比于Future,它的先进之处则在于 不仅仅只生产一个单一的结果,而是能够提供系列结果. Unlike Futures, DataSource can issue a series of results, rathe

Fresco 源码解析 - 利用 @DoNotSkip 来防止混淆

我们都知道,如果打开了混淆开关,代码 release 阶段会根据 proguard 规则进行混淆,但是有些实体类(例如 json 字符串对应的 model)需要进行序列化.反序列化,而序列化工具(例如 Gson.fastjson)是利用反射来一一对应 json 串的 key 和实体类的成员变量. 例如,我们定义一个 POJO 类型的 User 实体类: public class User { public String firstName; public String lastName; pub

Fresco源码解析 - Hierarachy-View-Controller

Fresco是一个MVC模型,由三大组件构成,它们的对应关系如下所示: M -> DraweeHierarchy V -> DraweeView C -> DraweeController M 所对应的 DraweeHierarchy 是一个有层次结构的数据结构,DraweeView 用来显示位于 DraweeHierarchy 最顶层的图像(top level drawable),DraweeController 则用来控制 DraweeHierarchy 的顶层图像是哪一个. o F

React源码解析——创建更新过程

一.ReactDOM.render 创建ReactRoot,并且根据情况调用root.legacy_renderSubtreeIntoContainer或者root.render,前者是遗留的 API 将来应该会删除,根据ReactDOM.render的调用情况也可以发现parentComponent是写死的null DOMRenderer.unbatchedUpdates制定不使用batchedUpdates,因为这是初次渲染,需要尽快完成. 原文地址:https://www.cnblogs.

JDK 源码解析 —— Executors ExecutorService ThreadPoolExecutor 线程池

零. 简介 Executors 是 Executor.ExecutorService.ThreadFactory.Callable 类的工厂和工具方法. 一. 源码解析 创建一个固定大小的线程池:通过重用共享无界队列里的线程来减少线程创建的开销.当所有的线程都在执行任务,新增的任务将会在队列中等待,直到一个线程空闲.由于在执行前失败导致的线程中断,如果需要继续执行接下去的任务,新的线程会取代它执行.线程池中的线程会一直存在,除非明确地 shutdown 掉. public static Exec

rocketmq源码解析之NamesrvController创建

说在前面 本次开始进行rocketmq源码解析,比较喜欢rocketmq的架构设计,rocketmq内嵌了namesrv注册中心保存了元数据,进行负载均衡.容错的一些处理,4.3以上支持消息事务,有管理控制台.命令行工具,底层namesrv与broker.client与server交互netty实现. 源码解析 创建NamesrvController,进入这个方法org.apache.rocketmq.namesrv.NamesrvStartup#main,再进入这个方法org.apache.r