全面解析Android的开源图片框架Universal-Image-Loader

2019-12-10 18:34:04丽君

第1行代码是检查ImageLoaderConfiguration是否初始化,这个初始化是在Application中进行的
12-21行主要是针对url为空的时候做的处理,第13行代码中,ImageLoaderEngine中存在一个HashMap,用来记录正在加载的任务,加载图片的时候会将ImageView的id和图片的url加上尺寸加入到HashMap中,加载完成之后会将其移除,然后将DisplayImageOptions的imageResForEmptyUri的图片设置给ImageView,最后回调给ImageLoadingListener接口告诉它这次任务完成了。

ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize()); 
 String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize); 
 engine.prepareDisplayTaskFor(imageAware, memoryCacheKey); 
 
 listener.onLoadingStarted(uri, imageAware.getWrappedView()); 
 
 Bitmap bmp = configuration.memoryCache.get(memoryCacheKey); 
 if (bmp != null && !bmp.isRecycled()) { 
  L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey); 
 
  if (options.shouldPostProcess()) { 
   ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, 
     options, listener, progressListener, engine.getLockForUri(uri)); 
   ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo, 
     defineHandler(options)); 
   if (options.isSyncLoading()) { 
    displayTask.run(); 
   } else { 
    engine.submit(displayTask); 
   } 
  } else { 
   options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE); 
   listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp); 
  } 
 } 

第1行主要是将ImageView的宽高封装成ImageSize对象,如果获取ImageView的宽高为0,就会使用手机屏幕的宽高作为ImageView的宽高,我们在使用ListView,GridView去加载图片的时候,第一页获取宽度是0,所以第一页使用的手机的屏幕宽高,后面的获取的都是控件本身的大小了
第7行从内存缓存中获取Bitmap对象,我们可以再ImageLoaderConfiguration中配置内存缓存逻辑,默认使用的是LruMemoryCache,这个类我在前面的文章中讲过
第11行中有一个判断,我们如果在DisplayImageOptions中设置了postProcessor就进入true逻辑,不过默认postProcessor是为null的,BitmapProcessor接口主要是对Bitmap进行处理,这个框架并没有给出相对应的实现,如果我们有自己的需求的时候可以自己实现BitmapProcessor接口(比如将图片设置成圆形的)