开源项目Universal Image Loader for Android

来源:互联网 发布:下载vb6.0软件 编辑:程序博客网 时间:2024/04/19 17:08
  1.   ImageLoader imageLoader = ImageLoader.getInstance();  
  2.         // 2. 使用默认配置  
  3.         ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);  
  4.         // 3. 初始化ImageLoader  
  5.         imageLoader.init(configuration);  
  6.         // 4. 显示图片时的配置  
  7.         displayImageOptions = new DisplayImageOptions.Builder().cacheInMemory().cacheOnDisc()  
  8.                 .bitmapConfig(Config.RGB_565).build();  
  9.         // 5.显示图片  
  10.         imageLoader.displayImage(uri, imageView, displayImageOptions);  


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

以下为参照原文进行的翻译

1.    Caching 默认不可用. 启用需要对DisplayImageOptions进行如下配置:

2.  // Create default options which will be usedfor every

3.  // displayImage(...) call if no options will be passed to this method

4.  DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()

5.          ...

6.          .cacheInMemory()

7.          .cacheOnDisc()

8.          ...

9.          .build();

10. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())

11.         ...

12.         .defaultDisplayImageOptions(defaultOptions)

13.         ...

14.         .build();

15. ImageLoader.getInstance().init(config);// Do it on Application start

16. // Then later, when you want to display image

17. ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used

or this way:

DisplayImageOptions options = new DisplayImageOptions.Builder()

        ...

        .cacheInMemory()

        .cacheOnDisc()

        ...

        .build();

ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used

18.  开启缓存后默认会缓存到外置SD卡如下地址(/sdcard/Android/data/[package_name]/cache).如果外置SD卡不存在,会缓存到手机. 缓存到Sd卡需要在Manifest文件中进行如下配置

19. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

20.  UIL是如何为ImageView精确定义需要的Bitmap的尺寸?它会搜索如下参数

o   获取ImageView真实的 width 和 height

o   获取 android:layout_width 和 android:layout_height 参数

o   获取 android:maxWidth and/or android:maxHeight 参数

o   从configuration (memoryCacheExtraOptions(int,int) option)获取 maximum width and/or height 参数

o   获取设备屏幕的 width and/or height  

所以如果你知道ImageView 的大约最大尺寸,就可以设置如下参数android:layout_width|android:layout_height or android:maxWidth|android:maxHeight 这样会有助于正确计算当前View所需要的Bitmap尺寸,并节约内存

如果你使用UIL时经常出现 OutOfMemoryError  那你可以尝试如下方法:

o   减少线程池大小 (.threadPoolSize(...)). 1 - 5 isrecommended.

o   在显示选项中使用 .bitmapConfig(Bitmap.Config.RGB_565) . RGB_565模式消耗的内存比ARGB_8888模式少两倍.

o   配置中使用 .memoryCache(newWeakMemoryCache()) 或者完全禁用在内存中缓存(don't call .cacheInMemory()).

o   在显示选项中使用 .imageScaleType(ImageScaleType.IN_SAMPLE_INT) 或者.imageScaleType(ImageScaleType.EXACTLY).

o   避免使用 RoundedBitmapDisplayer. 调用的时候它使用ARGB-8888模式创建了一个新的Bitmap对象来显示

对于内存缓存模式 (ImageLoaderConfiguration.memoryCache(...)) 你可以使用已经实现好的方法.

o   缓存只能使用强引用

§ LruMemoryCache (Least recently used bitmap is deleted when cache size limit isexceeded缓存大小超过指定值时,删除最近最少使用的bitmap) - Used by default for API >= 9

o   缓存使用弱引用和强引用:

§ UsingFreqLimitedMemoryCache (Least frequently used bitmap is deleted when cachesize limit is exceeded删除最少使用bitmap)

§ LRULimitedMemoryCache (Least recently used bitmap is deletedwhen cache size limit is exceeded删除最近最少使用bitmap) - Used by default for API < 9

§ FIFOLimitedMemoryCache (FIFO rule is used for deletion when cache sizelimit is exceeded先进先出规则删除bitmap)

§ LargestLimitedMemoryCache (The largest bitmap is deleted when cache sizelimit is exceeded删除最大的bitmap)

§ LimitedAgeMemoryCache (Decorator. Cached object is deleted when its ageexceeds defined value缓存对象超过定义的时间后删除)

o   缓存只能使用弱引用:

§ WeakMemoryCache (Unlimited cache不限制缓存)

21.  本地缓存模式可以使用以下以实现的方法 (ImageLoaderConfiguration.discCache(...)):

o   UnlimitedDiscCache (The fastest cache, doesn't limit cache size不限制缓存大小) - Used by default

o   TotalSizeLimitedDiscCache (Cache limited by total cache size. If cache size exceedsspecified limit then file with the most oldest last usage date will be deleted设置总缓存大小,超过时删除最久之前的缓存)

o   FileCountLimitedDiscCache (Cache limited by file count. If file count incache directory exceeds specified limit then file with the most oldest lastusage date will be deleted. Use it if your cached files are of about the samesize.设置总缓存文件数量,当到达警戒值时,删除最久之前的缓存。如果文件的大小都一样的时候,可以使用该模式)

o   LimitedAgeDiscCache (Size-unlimited cache with limited files' lifetime.If age of cached file exceeds defined limit then it will be deleted from cache.不限制缓存大小,但是设置缓存时间,到期后删除)

NOTE: UnlimitedDiscCache 比其他方式快30%以上.

22.  To displaybitmap (DisplayImageOptions.displayer(...)) you can usealready prepared implementations:

o   RoundedBitmapDisplayer (Displays bitmap with rounded corners)

o   FadeInBitmapDisplayer (Displays image with "fade in" animation)

23.  To avoid list(grid, ...) scrolling lags you can use PauseOnScrollListener:

24. boolean pauseOnScroll = false; // or true

25. boolean pauseOnFling = true; // or false

26. PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll,pauseOnFling);

27. listView.setOnScrollListener(listener);


 这是 一个开源的Android关于下载显示图片的工具类,在这个下载包里面偶jar文件,用于我们导入项目使用,具体使用方法在包里面也含有。下面是一个例子:

ImageView imageView = ...String imageUrl = "http://site.com/image.png"; // or "file:///mnt/sdcard/images/image.jpg"ProgressBar spinner = ...File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "UniversalImageLoader/Cache");// Get singletone instance of ImageLoaderImageLoader imageLoader = ImageLoader.getInstance();// Create configuration for ImageLoader (all options are optional, use only those you really want to customize)ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())            .memoryCacheExtraOptions(480, 800) // max width, max height            .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75) // Can slow ImageLoader, use it carefully (Better don't use it)            .threadPoolSize(3)            .threadPriority(Thread.NORM_PRIORITY - 1)            .denyCacheImageMultipleSizesInMemory()            .offOutOfMemoryHandling()            .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation            .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation            .discCacheFileNameGenerator(new HashCodeFileNameGenerator())            .imageDownloader(new URLConnectionImageDownloader(5 * 1000, 20 * 1000)) // connectTimeout (5 s), readTimeout (20 s)            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())            .enableLogging()            .build();// Initialize ImageLoader with created configuration. Do it once on Application start.imageLoader.init(config);
// Creates display image options for custom display task (all options are optional)DisplayImageOptions options = new DisplayImageOptions.Builder()           .showStubImage(R.drawable.stub_image)           .showImageForEmptyUri(R.drawable.image_for_empty_url)           .cacheInMemory()           .cacheOnDisc()           .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)           .displayer(new RoundedBitmapDisplayer(20))           .build();// Load and display imageimageLoader.displayImage(imageUrl, imageView, options, new ImageLoadingListener() {    @Override    public void onLoadingStarted() {       spinner.show();    }    @Override    public void onLoadingFailed(FailReason failReason) {        spinner.hide();    }    @Override    public void onLoadingComplete(Bitmap loadedImage) {        spinner.hide();    }    @Override    public void onLoadingCancelled() {        // Do nothing    }});
// Just load imageDisplayImageOptions options = new DisplayImageOptions.Builder()           .cacheInMemory()           .cacheOnDisc()           .imageScaleType(ImageScaleType.IN_SAMPLE_INT)           .displayer(new FakeBitmapDisplayer())           .build();ImageSize minImageSize = new ImageSize(120, 80);imageLoader.loadImage(context, imageUrl, minImageSize, options, new SimpleImageLoadingListener() {    @Override    public void onLoadingComplete(Bitmap loadedImage) {        // Do whatever you want with loaded Bitmap    }});
四、使用信息

缓存不是默认启用如果你想将被缓存在内存中加载图像和/或那么你应该启用缓存displayimageoptions方式如下

// Create default options which will be used for every //  displayImage(...) call if no options will be passed to this methodDisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()        ...        .cacheInMemory()        .cacheOnDisc()        ...        .build();ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())        ...        .defaultDisplayImageOptions(defaultOptions)        ...        .build();ImageLoader.getInstance().init(config); // Do it on Application start
// Then later, when you want to display imageImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
使用Android-Universal-Image-Loader的例子程序:
  • MediaHouse, UPnP/DLNA Browser
  • Деловой Киров
  • Бизнес-завтрак
  • Menu55
  • SpokenPic
  • Kumir
  • EUKO 2012
  • TuuSo Image Search
  • Газета Стройка
  • Prezzi Benzina (AndroidFuel)
  • Quiz Guess The Guy
  • Volksempfänger (alpha)
  • ROM Toolbox Lite | Pro
  • London 2012 Games
  • 카톡 이미지 - 예쁜 프로필 이미지
  • dailyPen
  • TK App
  • Mania!
  • Stadium Astro
  • Chef Astro
  • Lafemme Fashion Finder
  • FastPaleo
  • Live Soccer Scores
  • friendizer
  • LowPrice lowest book price
  • bluebee
  • Game PromoBox
  • EyeEm - Photo Filter Camera
  • Festival Wallpaper
  • Gaudi Hall
  • Spocal
  • PhotoDownloader for Facebook 

大家 可以好好看看这些例子,他们是如何把这个组件应用到程序里面的。这个开源程序的下载地址是:https://nodeload.github.com/nostra13/Android-Universal-Image-Loader/zipball/master


转载: http://blog.csdn.net/hkg1pek/article/details/9091931  这个还有译文(很详细)

            http://blog.csdn.net/jodan179/article/details/8191183

 


原创粉丝点击