一、說明文檔以及相關細節java
All manipulations are held by the ImageLoader class. It is a singletone, so to get a single instance of the class, you should call the getInstance() method. Before using ImageLoader to its intended purpose (to display images), you should initialize its configuration - ImageLoaderConfiguration using the init (...) method. Well, then you can use all variations of the displayImage(...) method with a clear conscience.android
全部的操做都由ImageLoader控制。該類使用單例設計模式,因此若是要獲取該類的實例,須要調用getInstance()方法。在使用ImageLoader顯示圖片以前,你首先要初始化它的配置,調用ImageLoaderConfiguration的init()方法,而後你就能夠實現各類的顯示了。web
In general, the easiest option of using ImageLoader (with the default configuration) is shown below:設計模式
一般狀況下,ImageLoader最簡單的使用方法以下(使用默認的配置選項):緩存
ImageView imageView = ... // view, where the image will be displayed網絡
String imageUrl = ... // image URL (e.g. "http://site.com/image.png", "file:///mnt/sdcard/img/image.jpg")app
ImageLoader imageLoader = ImageLoader.getInstance();less
imageLoader.init(ImageLoaderConfiguration.createDefault(context));ide
imageLoader.displayImage(imageUrl, imageView);ui
Now, let’s consider the full functionality.
如今讓咱們討論下他的所有功能:
As you already know, you first need to initialize the ImageLoader using the configuration object. As the ImageLoader is a singleton, then it should be initialized only once for application launching. I would recommend doing it in an overloaded Application.onCreate(). A reinitializing of an already initialized ImageLoader will have no effect.
So, we create a configuration, it is an object of the ImageLoaderConfiguration class. We create it using theBuilder:
就像你已經知道的,首先,你須要使用ImageLoaderConfiguration對象來初始化ImageLoader。因爲ImageLoader是單例,因此在程序開始的時候只須要初始化一次就行了。建議你在Activity的onCreate()方法中初始化。若是一個ImageLoader已經初始化過,再次初始化不會有任何效果。下面咱們經過ImageLoaderConfiguration.Builder建立一個設置
File cacheDir = StorageUtils.getCacheDirectory(context,
"UniversalImageLoader/Cache");
ImageLoaderConfiguration config = new
ImageLoaderConfiguration.Builder(getApplicationContext())
.maxImageWidthForMemoryCache(800)
.maxImageHeightForMemoryCache(480)
.httpConnectTimeout(5000)
.httpReadTimeout(20000)
.threadPoolSize(5)
.threadPriority(Thread.MIN_PRIORITY + 3)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new UsingFreqLimitedCache(2000000)) // You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.build();
Let’s consider each option:
下面上咱們來討論一下每一個選項:
• maxImageWidthForMemoryCache() and maxImageHeightForMemoryCache() is used for decoding images into Bitmap objects. In order not to store a full-sized image in the memory, it is reduced to a size determined from the values of ImageView parameters, where the image is loaded: maxWidth and maxHeight (first stage),layout_width and layout_height (second stage). If these parameters are not defined (values fill_parentand wrap_content are considered as uncertain), then dimensions specified by settings maxImageWidthForMemoryCache() and maxImageHeightForMemoryCache() are taken. The size of the original image is reduced by 2 times (recommended for fast decoding), till the width or height becomes less than the specified values;
•用於將圖片解碼爲Bitmap對象。爲了不將原圖存到內存中,系統會根據ImageView的參數來縮小圖片的尺寸,這些參數包括maxWidth 、maxHeight 、layout_width 、layout_height .若是這些參數沒有指定,尺寸將會根據maxImageWidthForMemoryCache和maxImageHeightForMemoryCache指定。原始圖片的尺寸將會被縮減兩次,知道寬和高比指定的值小。
o Default values - size of the device’s screen.
o 默認值 - 設備屏幕的尺寸
• httpConnectTimeout() sets the maximum waiting time (in milliseconds) for establishing an HTTP connection;
• 設置創建HTTP鏈接的最大超時時間
o Default value - 5 seconds
o 默認值 - 5秒
• httpReadTimeout() sets the maximum time (in milliseconds) for loading an image from the Web;
• 設置從網絡上加載圖片的最大超時時間
o Default value - 30 seconds
o 默認值 - 30秒
• threadPoolSize() sets size of the thread pool. Each task on image loading and displaying is performed in a separate thread, and those threads, in which the image uploading from the Web occurs, get to the pool. Thus, the pool size determines the number of threads running simultaneously. Setting of a large pool size can significantly reduce the speed of the UI, for example, list scrolling could slow down.
• 設置線程池的大小。每個加載和顯示圖片的任務都運行在獨立的線程中,所以,線程池的大小決定了能夠同時運行的線程數,若是設置的過大,將會下降UI線程的反應速度,好比List滑動時可能會卡頓。
o Default value - 5
o 默認值 - 5
• threadPriority() sets priority of all threads in the system (from 1 to 10), in which tasks are performed;
•設置當前線程的優先級(1 -- 10)
o Default value - 4
o 默認值 - 4
• calling denyCacheImageMultipleSizesInMemory() imposes a ban on storing different sizes of the same image in the memory. As full-size images are stored in the disk cache, and when loading into memory, they are reduced to the size of ImageView, in which they should be displayed, then there are cases when the same image has to be displayed first in a small view, and then in a big one. At the same time, two Bitmaps of different sizes representing the same image will be stored in the memory. This is the default behavior.
• 調用該方法會禁止在內存中緩存同一張圖片的多個尺寸。當把本地圖片加載到內存中時,首先會把圖片縮減至要顯示的ImageView的大小,所以可能會出現一種情況,就是會首先顯示一張圖的小圖,而後再顯示這張圖的大圖。這種狀況下,同一張圖片的兩種尺寸的Bitmap會被存儲在內存中,這是默認的操做
The denyCacheImageMultipleSizesInMemory() instruction ensures deletion of the previous size of the loaded image from cache in the memory.
該方法會確保刪除已加載圖片緩存在內存中的其餘尺寸的緩存。
• Using memoryCache(), you can specify the implementation of cache in the memory. You can use ready-made solutions (they all are realizations of limited size-cache; where by exceeding cache size, an object is removed from it by a certain algorithm):
• 調用該方法,你能夠指定在內存中緩存的實現。你可使用以下這些已有的解決方案
o FIFOLimitedCache (the object is removed on the basis of First-In-First-Out)
o 按照FIFO規則清理內存
o LargestLimitedCache (the largest-sized object is removed)
o 移除最大的緩存
o UsingAgeLimitedCache (the object with the oldest date of access is removed)
o 按照訪問時間,移除最久以前的緩存
o UsingFreqLimitedCache (the most rarely used object is removed)
o 按照使用頻率,移除最少使用的緩存
Alternatively, you can implement your own version of the cache by implementing the interface MemoryCacheAware<String, Bitmap>;
固然,你也經過實現接口 MemoryCacheAware<String, Bitmap>來實現一個自定義的清除緩存的方法,
o Default value - UsingFreqLimitedCache with memory limit to 2 MB
o 默認值 - UsingFreqLimitedCache ,緩存大小2MB
memoryCacheSize() sets the maximum cache size in the memory. In this case, the default cache is used -UsingFreqLimitedCache.
設置內存中緩存的大小。這種狀況下,默認的緩存方法是用UsingFreqLimitedCache
o Default value - 2 MB
o 默認值 - 2MB
• Using discCache(), you can define cash implementation in the file system. You can use ready-made solutions (where the files matching certain URLs are named as hash codes of these URLs):
• discCache()設置本地緩存。你可使用如下已實現的方法
o UnlimitedDiscCache (usual cache, no restrictions)
o 不限制緩存大小
o FileCountLimitedDiscCache (cache with limited size)
o 限制緩存的文件數量(樓主可能把註釋寫反了)
o TotalSizeLimitedDiscCache (cache with limited files number)
o 限制緩存文件的總大小
Alternatively, you can define your own cache implementation by DiscCacheAware interface.
固然你能夠實現接口DiscCacheAware 來自定義緩存的實現方法
o Default value - UnlimitedDiscCache
o 默認值 - UnlimitedDiscCache
• discCacheSize(int) specifies the maximum cache size in the file system. In this case, the TotalSizeLimitedDiscCache is used.
• 指定在本地的最大緩存大小。在這種狀況下,TotalSizeLimitedDiscCache 會被使用
• discCacheFileCount(int) specifies the maximum number of files in the disk cache. In this case, the FileCountLimitedDiscCache is used.
• 指定在本地緩存的文件數量。在這種狀況下,FileCountLimitedDiscCache 會被使用
• Using defaultDisplayImageOptions(), you can set image displaying options, which will be used for all calls of the displayimage(...) method, where custom options were not passed.
•使用defaultDisplayImageOptions你能夠設置圖片的顯示選項,這些選項會在調用displayimage(...)的時候被使用。
I’ll discuss these options in details below.
在下面我會討論這些選項
We can construct a configuration object ourselves or trust a developer (i.e. me) and use the default configuration:
咱們能夠自定義配置選項,也能夠trust me,使用我提供的默認選項:
ImageLoaderConfiguration config =
ImageLoaderConfiguration.createDefault(context);
Thus, the configuration is created. Now, the ImageLoader can be initialized with it:
這樣,一個設置就建立了,以後,你就能夠用它來初始化ImageLoader
ImageLoader.getInstance().init(config);
That's all, the ImageLoader is ready to use. I'll tell you about this in the next article.
這時候ImageLoader就可使用了。
二、使用範例
1.自定義XXXAppllication類,初始化ImageLoader
public class XXXApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
//這下面的參數就不一一解釋了
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.discCacheSize(50 * 1024 * 1024)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.discCacheFileCount(100)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
}
2.在AndroidManifest.xml文件的application標籤里加入
[java]
android:name=".XXXApplication"
3.使用imageloader
[java]
public class ImageManager{
public static void Load(String imgUrl,ImageView imageView){
ImageLoader.getInstance().displayImage(imgUrl, imageView);
}
public static void Load(String imgUrl,ImageView imageView,DisplayImageOptions o){
ImageLoader.getInstance().displayImage(imgUrl, imageView,o);
}
}
固然對於圖片的顯示上是能夠不一樣的狀況採用不一樣的配置來顯示,若是用默認構造方法的話,那麼顯示的效果就是你在
XXXAppllication類中定義好的效果了,若是,有一部分是須要特殊處理的,好比說要有圓角,那麼就須要本身單獨的再寫一下配置,在當前的類的構造方法或者onCreate();中初始化,以下
private DisplayImageOptions options;
public MyPhotoEditAdapter(Context context,List<String> imgUrlList){
this.context=context;
this.imgUrlList=imgUrlList;
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.icon_default2x)
.showImageForEmptyUri(R.drawable.icon_default2x)
.cacheOnDisc() // 緩存用
.displayer(new RoundedBitmapDisplayer(8)) // 圖片圓角顯示,值爲整數
.build();
}
在使用的時候一行代碼就能夠直接顯示了
ImageLoader.getInstance().displayImage(圖片的網絡地址Url, 顯示圖片的控件ImageView,這個就是你本身寫的配置了options);
使用默認配置的方式顯示圖片就更簡單了
ImageLoader.getInstance().displayImage(圖片的網絡地址uri,顯示圖片的控件 imageView);
最後千萬要記得
在AndroidManifest.xml文件的application標籤里加入
android:name=".XXXApplication"
不然你的程序就會報錯,提示ImageLoader沒有實例化
OK,簡單的解析就到這裏,歡迎你們一塊兒討論