標籤:mit grid create shc raw port 圖片顯示 功能 ssi
轉載請註明本文出自xiaanming的部落格(http://blog.csdn.net/xiaanming/article/details/26810303)。請尊重他人的辛勤勞動成果,謝謝!
大家好!差點兒相同兩個來月沒有寫文章了。前段時間也是在忙換工作的事,準備筆試面試什麼的事情,如今新工作找好了,新工作自己也比較愜意。唯一遺憾的就是自己要去一個新的城市,新的環境新的開始。希望自己能儘快的適應新環境,如今在準備交接的事情,自己也有一些時間了,所以就繼續給大家分享Android方面的東西。
相信大家平時做Android應用的時候,多少會接觸到非同步載入圖片,或者載入大量圖片的問題。而載入圖片我們常常會遇到很多的問題,比方說圖片的錯亂。OOM等問題,對於新手來說,這些問題解決起來會比較吃力,所以就有非常多的開源圖片載入架構應運而生,比較著名的就是Universal-Image-Loader。相信非常多朋友都聽過或者使用過這個強大的圖片載入架構,今天這篇文章就是對這個架構的基本介紹以及使用,主要是協助那些沒有使用過這個架構的朋友們。
該項目存在於Github上面https://github.com/nostra13/Android-Universal-Image-Loader,我們能夠先看看這個開源庫存在哪些特徵
- 多線程下載圖片。圖片能夠來源於網路,檔案系統,專案檔夾assets中以及drawable中等
- 支援任意的配置ImageLoader,比如線程池,圖片下載器。記憶體緩衝策略,硬碟緩衝策略。圖片顯示選項以及其它的一些配置
- 支援圖片的記憶體緩衝,檔案系統快取或者SD卡緩衝
- 支援圖片下載過程的監聽
- 依據控制項(ImageView)的大小對Bitmap進行裁剪。降低Bitmap佔用過多的記憶體
- 較好的控製圖片的載入過程,比如暫停圖片載入,又一次開始載入圖片,一般使用在ListView,GridView中,滑動過程中暫停載入圖片,停止滑動的時候去載入圖片
- 提供在較慢的網路下對圖片進行載入
當然上面列舉的特性可能不全,要想瞭解一些其它的特性僅僅能通過我們的使用慢慢去發現了,接下來我們就看看這個開源庫的簡單使用吧
建立一個Android項目,下載JAR包加入到projectlibs檔案夾下
建立一個MyApplication繼承Application,並在onCreate()中建立ImageLoader的配置參數,並初始化到ImageLoader中代碼例如以下
package com.example.uil;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import android.app.Application;public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//建立預設的ImageLoader配置參數ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);//Initialize ImageLoader with configuration.ImageLoader.getInstance().init(configuration);}}ImageLoaderConfiguration是圖片載入器ImageLoader的配置參數,使用了建造者模式,這裡是直接使用了createDefault()方法建立一個預設的ImageLoaderConfiguration,當然我們還能夠自己設定ImageLoaderConfiguration。設定例如以下
File cacheDir = StorageUtils.getCacheDirectory(context);ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions .diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null) .taskExecutor(...) .taskExecutorForCachedImages(...) .threadPoolSize(3) // default .threadPriority(Thread.NORM_PRIORITY - 1) // default .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiscCache(cacheDir)) // default .diskCacheSize(50 * 1024 * 1024) .diskCacheFileCount(100) .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default .imageDownloader(new BaseImageDownloader(context)) // default .imageDecoder(new BaseImageDecoder()) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() .build();
上面的這些就是全部的選項配置。我們在項目中不須要每個都自己設定,一般使用createDefault()建立的ImageLoaderConfiguration就能使用,然後調用ImageLoader的init()方法將ImageLoaderConfiguration參數傳遞進去,ImageLoader使用單例模式。
配置Android Manifest檔案
<manifest> <uses-permission android:name="android.permission.INTERNET" /> <!-- Include next permission if you want to allow UIL to cache images on SD card --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... <application android:name="MyApplication"> ... </application></manifest>
接下來我們就能夠來載入圖片了,首先我們定義好Activity的布局檔案
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:layout_gravity="center" android:id="@+id/image" android:src="@drawable/ic_empty" android:layout_width="wrap_content" android:layout_height="wrap_content" /></FrameLayout>
裡面僅僅有一個ImageView,非常easy,接下來我們就去載入圖片。我們會發現ImageLader提供了幾個圖片載入的方法,主要是這幾個displayImage(), loadImage(),loadImageSync()。loadImageSync()方法是同步的,android4.0有個特性。網路操作不能在主線程,所以loadImageSync()方法我們就不去使用
.
loadimage()載入圖片
我們先使用ImageLoader的loadImage()方法來載入網狀圖片
final ImageView mImageView = (ImageView) findViewById(R.id.image);String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";ImageLoader.getInstance().loadImage(imageUrl, new ImageLoadingListener() {@Overridepublic void onLoadingStarted(String imageUri, View view) {}@Overridepublic void onLoadingFailed(String imageUri, View view,FailReason failReason) {}@Overridepublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {mImageView.setImageBitmap(loadedImage);}@Overridepublic void onLoadingCancelled(String imageUri, View view) {}});傳入圖片的url和ImageLoaderListener, 在回調方法onLoadingComplete()中將loadedImage設定到ImageView上面即可了,假設你認為傳入ImageLoaderListener太複雜了,我們能夠使用SimpleImageLoadingListener類,該類提供了ImageLoaderListener介面方法的空實現,使用的是預設適配器模式
final ImageView mImageView = (ImageView) findViewById(R.id.image);String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";ImageLoader.getInstance().loadImage(imageUrl, new SimpleImageLoadingListener(){@Overridepublic void onLoadingComplete(String imageUri, View view,Bitmap loadedImage) {super.onLoadingComplete(imageUri, view, loadedImage);mImageView.setImageBitmap(loadedImage);}});假設我們要指定圖片的大小該怎麼辦呢,這也好辦,初始化一個ImageSize對象,指定圖片的寬和高。代碼例如以下
final ImageView mImageView = (ImageView) findViewById(R.id.image);String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";ImageSize mImageSize = new ImageSize(100, 100);ImageLoader.getInstance().loadImage(imageUrl, mImageSize, new SimpleImageLoadingListener(){@Overridepublic void onLoadingComplete(String imageUri, View view,Bitmap loadedImage) {super.onLoadingComplete(imageUri, view, loadedImage);mImageView.setImageBitmap(loadedImage);}});
上面僅僅是非常easy的使用ImageLoader來載入網狀圖片,在實際的開發中,我們並不會這麼使用,那我們尋常會怎麼使用呢?我們會用到DisplayImageOptions。他能夠配置一些圖片顯示的選項,比方圖片在載入中ImageView顯示的圖片,是否須要使用記憶體緩衝,是否須要使用檔案快取等等。可供我們選擇的配置例如以下
DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) // resource or drawable .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable .showImageOnFail(R.drawable.ic_error) // resource or drawable .resetViewBeforeLoading(false) // default .delayBeforeLoading(1000) .cacheInMemory(false) // default .cacheOnDisk(false) // default .preProcessor(...) .postProcessor(...) .extraForDownloader(...) .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default .decodingOptions(...) .displayer(new SimpleBitmapDisplayer()) // default .handler(new Handler()) // default .build();
我們將上面的代碼略微改動下
final ImageView mImageView = (ImageView) findViewById(R.id.image);String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";ImageSize mImageSize = new ImageSize(100, 100);//顯示圖片的配置DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();ImageLoader.getInstance().loadImage(imageUrl, mImageSize, options, new SimpleImageLoadingListener(){@Overridepublic void onLoadingComplete(String imageUri, View view,Bitmap loadedImage) {super.onLoadingComplete(imageUri, view, loadedImage);mImageView.setImageBitmap(loadedImage);}});
我們使用了DisplayImageOptions來配置顯示圖片的一些選項。這裡我加入了將圖片緩衝到記憶體中已經緩衝圖片到檔案系統中,這樣我們就不用操心每次都從網路中去載入圖片了,是不是非常方便呢,可是DisplayImageOptions選項中有些選項對於loadImage()方法是無效的。比方showImageOnLoading, showImageForEmptyUri等,
displayImage()載入圖片
接下來我們就來看看網狀圖片載入的還有一個方法displayImage(),代碼例如以下
final ImageView mImageView = (ImageView) findViewById(R.id.image);String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";//顯示圖片的配置DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub).showImageOnFail(R.drawable.ic_error).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);
從上面的代碼中,我們能夠看出,使用displayImage()比使用loadImage()方便非常多,也不須要加入ImageLoadingListener介面,我們也不須要手動設定ImageView顯示Bitmap對象。直接將ImageView作為參數傳遞到displayImage()中即可了,圖片顯示的配置選項中,我們加入了一個圖片載入中ImageVIew上面顯示的圖片。以及圖片載入出現錯誤顯示的圖片。效果例如以下,剛開始顯示ic_stub圖片,假設圖片載入成功顯示圖片。載入產生錯誤顯示ic_error
這種方法使用起來比較方便,並且使用displayImage()方法 他會依據控制項的大小和imageScaleType來自己主動裁剪圖片,我們改動下MyApplication,開啟Log列印
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//建立預設的ImageLoader配置參數ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).writeDebugLogs() //列印log資訊.build();//Initialize ImageLoader with configuration.ImageLoader.getInstance().init(configuration);}}
我們來看片載入的Log資訊
第一條資訊中。告訴我們開始載入圖片,列印出圖片的url以及圖片的最大寬度和高度,圖片的寬高預設是裝置的寬高,當然假設我們非常清楚圖片的大小,我們也能夠去設定這個大小,在ImageLoaderConfiguration的選項中memoryCacheExtraOptions(int maxImageWidthForMemoryCache, int maxImageHeightForMemoryCache)
第二條資訊顯示我們載入的圖片來源於網路
第三條資訊顯示圖片的原始大小為1024 x 682 經過裁剪變成了512 x 341
第四條顯示圖片加入到了記憶體緩衝中,我這裡沒有加入到sd卡中,所以沒有加入檔案快取的Log
我們在載入網狀圖片的時候。常常有須要顯示圖片下載進度的需求。Universal-Image-Loader當然也提供這種功能,僅僅須要在displayImage()方法中傳入ImageLoadingProgressListener介面即可了。代碼例如以下
imageLoader.displayImage(imageUrl, mImageView, options, new SimpleImageLoadingListener(), new ImageLoadingProgressListener() {@Overridepublic void onProgressUpdate(String imageUri, View view, int current,int total) {}});由於displayImage()方法中帶ImageLoadingProgressListener參數的方法都有帶ImageLoadingListener參數,所以我這裡直接new 一個SimpleImageLoadingListener,然後我們就能夠在回調方法onProgressUpdate()得到圖片的載入進度。
載入其它來源的圖片
使用Universal-Image-Loader架構不僅能夠載入網狀圖片,還能夠載入sd卡中的圖片,Content provider等,使用也非常easy,僅僅是將圖片的url稍加的改變下即可了,以下是載入檔案系統的圖片
//顯示圖片的配置DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub).showImageOnFail(R.drawable.ic_error).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();final ImageView mImageView = (ImageView) findViewById(R.id.image);String imagePath = "/mnt/sdcard/image.png";String imageUrl = Scheme.FILE.wrap(imagePath);//String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";imageLoader.displayImage(imageUrl, mImageView, options);
當然還有來源於Content provider,drawable,assets中。使用的時候也非常easy,我們僅僅須要給每個圖片來源的地方加上Scheme包裹起來(Content provider除外)。然後當做圖片的url傳遞到imageLoader中。Universal-Image-Loader架構會依據不同的Scheme擷取到輸入資料流
//圖片來源於Content providerString contentprividerUrl = "content://media/external/audio/albumart/13";//圖片來源於assetsString assetsUrl = Scheme.ASSETS.wrap("image.png");//圖片來源於String drawableUrl = Scheme.DRAWABLE.wrap("R.drawable.image");
GirdView,ListView載入圖片
相信大部分人都是使用GridView,ListView來顯示大量的圖片。而當我們高速滑動GridView。ListView。我們希望能停止圖片的載入,而在GridView,ListView停止滑動的時候載入當前介面的圖片,這個架構當然也提供這個功能,使用起來也非常easy。它提供了PauseOnScrollListener這個類來控制ListView,GridView滑動過程中停止去載入圖片,該類使用的是代理模式
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
第一個參數就是我們的圖片載入對象ImageLoader, 第二個是控制是否在滑動過程中暫停載入圖片。假設須要暫停傳true即可了,第三個參數控制猛的滑動介面的時候圖片是否載入
OutOfMemoryError
儘管這個架構有非常好的緩衝機制,有效避免了OOM的產生,一般的情況下產生OOM的機率比較小,可是並不能保證OutOfMemoryError永遠不發生,這個架構對於OutOfMemoryError做了簡單的catch,保證我們的程式遇到OOM而不被crash掉。可是假設我們使用該架構常常發生OOM,我們應該怎麼去改善呢?
- 降低線程池中線程的個數。在ImageLoaderConfiguration中的(.threadPoolSize)中配置,推薦配置1-5
- 在DisplayImageOptions選項中配置bitmapConfig為Bitmap.Config.RGB_565,由於預設是ARGB_8888, 使用RGB_565會比使用ARGB_8888少消耗2倍的記憶體
- 在ImageLoaderConfiguration中配置圖片的記憶體緩衝為memoryCache(new WeakMemoryCache()) 或者不使用記憶體緩衝
- 在DisplayImageOptions選項中設定.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY)
通過上面這些,相信大家對Universal-Image-Loader架構的使用已經非常的瞭解了。我們在使用該架構的時候盡量的使用displayImage()方法去載入圖片,loadImage()是將圖片對象回調到ImageLoadingListener介面的onLoadingComplete()方法中,須要我們手動去設定到ImageView上面。displayImage()方法中,對ImageView對象使用的是Weak references。方便記憶體回收行程回收ImageView對象。假設我們要載入固定大小的圖片的時候。使用loadImage()方法須要傳遞一個ImageSize對象,而displayImage()方法會依據ImageView對象的測量值,或者android:layout_width and android:layout_height設定的值。或者android:maxWidth and/or android:maxHeight設定的值來裁剪圖片
今天就給大家分享到這裡,有不明確的地方在以下留言,我會盡量為大家解答的。下一篇文章我將繼續更深入的分析這個架構,希望大家繼續關注。
Android 開源架構Universal-Image-Loader全然解析(一)--- 基本介紹及使用