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

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

第6行的downloadImage()方法是负责下载图片,并将其保持到文件缓存中,将下载保存Bitmap的进度回调到IoUtils.CopyListener接口的onBytesCopied(int current, int total)方法中,所以我们可以设置ImageLoadingProgressListener接口来获取图片下载保存的进度,这里保存在文件系统中的图片是原图
第16-17行,获取ImageLoaderConfiguration是否设置保存在文件系统中的图片大小,如果设置了maxImageWidthForDiskCache和maxImageHeightForDiskCache,会调用resizeAndSaveImage()方法对图片进行裁剪然后在替换之前的原图,保存裁剪后的图片到文件系统的,之前有同学问过我说这个框架保存在文件系统的图片都是原图,怎么才能保存缩略图,只要在Application中实例化ImageLoaderConfiguration的时候设置maxImageWidthForDiskCache和maxImageHeightForDiskCache就行了

if (bmp == null) return; // listener callback already was fired 
 
    checkTaskNotActual(); 
    checkTaskInterrupted(); 
 
    if (options.shouldPreProcess()) { 
     L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey); 
     bmp = options.getPreProcessor().process(bmp); 
     if (bmp == null) { 
      L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey); 
     } 
    } 
 
    if (bmp != null && options.isCacheInMemory()) { 
     L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey); 
     configuration.memoryCache.put(memoryCacheKey, bmp); 
    } 

接下来这里就简单了,6-12行是否要对Bitmap进行处理,这个需要自行实现,14-17就是将图片保存到内存缓存中去

DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom); 
  runTask(displayBitmapTask, syncLoading, handler, engine); 

最后这两行代码就是一个显示任务,直接看DisplayBitmapTask类的run()方法

@Override 
 public void run() { 
  if (imageAware.isCollected()) { 
   L.d(LOG_TASK_CANCELLED_IMAGEAWARE_COLLECTED, memoryCacheKey); 
   listener.onLoadingCancelled(imageUri, imageAware.getWrappedView()); 
  } else if (isViewWasReused()) { 
   L.d(LOG_TASK_CANCELLED_IMAGEAWARE_REUSED, memoryCacheKey); 
   listener.onLoadingCancelled(imageUri, imageAware.getWrappedView()); 
  } else { 
   L.d(LOG_DISPLAY_IMAGE_IN_IMAGEAWARE, loadedFrom, memoryCacheKey); 
   displayer.display(bitmap, imageAware, loadedFrom); 
   engine.cancelDisplayTaskFor(imageAware); 
   listener.onLoadingComplete(imageUri, imageAware.getWrappedView(), bitmap); 
  } 
 }