1. ImageLoaderimageLoader=ImageLoader.getInstance();
  2. //2.使用默认配置
  3. ImageLoaderConfigurationconfiguration=ImageLoaderConfiguration.createDefault(this);
  4. //3.初始化ImageLoader
  5. imageLoader.init(configuration);
  6. //4.显示图片时的配置
  7. displayImageOptions=newDisplayImageOptions.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.DisplayImageOptionsdefaultOptions= newDisplayImageOptions.Builder()

5....

6..cacheInMemory()

7..cacheOnDisc()

8....

9..build();

10.ImageLoaderConfigurationconfig= newImageLoaderConfiguration.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:

DisplayImageOptionsoptions= newDisplayImageOptions.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-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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

o获取ImageView真实的width和height

o获取android:layout_widthandroid:layout_height参数

o获取android:maxWidthand/orandroid:maxHeight参数

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

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

所以如果你知道ImageView的大约最大尺寸,就可以设置如下参数android:layout_width|android:layout_heightorandroid: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 usedbitmap is deletedwhen cache size limit is exceeded删除最近最少使用bitmap) -Used by default for API < 9

§FIFOLimitedMemoryCache(FIFOrule 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(...)):

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

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

oFileCountLimitedDiscCache(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.设置总缓存文件数量,当到达警戒值时,删除最久之前的缓存。如果文件的大小都一样的时候,可以使用该模式)

oLimitedAgeDiscCache(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:

oRoundedBitmapDisplayer(Displays bitmap with rounded corners)

oFadeInBitmapDisplayer(Displays image with "fade in" animation)

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

24.booleanpauseOnScroll= false;// or true

25.booleanpauseOnFling= true;// or false

26.PauseOnScrollListenerlistener= newPauseOnScrollListener(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


更多相关文章

  1. Android测量字符串所占UI的大小
  2. android textview宽度固定的情况下字体大小自适应
  3. Android 混合H5开发两种模式
  4. android的EventBus模式 解决各种handler,asynctask的问题,能够帮助
  5. Android 如何获取apk大小与时间
  6. android surfaceView控制视频显示大小
  7. android图片缩放(指定大小) drawable获取图片后怎么设置图片大小
  8. Android 中关于 【Cursor】 类的介绍、数据库和设计模式
  9. android 获取APP大小及其清理缓存内容

随机推荐

  1. Android——效率提升之AndroidStudio快速
  2. Android(安卓)Camera从Camera HAL1到Came
  3. Android(安卓)JNI HelloWorld实现
  4. 一个简单的Android程序的登录界面
  5. Android中的Context----既熟悉又陌生的朋
  6. Android(安卓)ApiDemos示例解析(101):Vie
  7. Android(安卓)EditText边框颜色的selecto
  8. Android(安卓)DDMS如何使用?
  9. Android(安卓)Studio中添加阿里云Maven仓
  10. IPhone开发资料整理