1. 圖像_UIL
- 主頁: https://github.com/nostra13/Android-Universal-Image-Loader
- 使用步驟:
添加依賴: compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
-
添加權限:
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
在Application或Activity中進行初始化配置
// ImageLoaderConfiguration 詳細配置 File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache"); // 自定義緩存文件夾 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // 指定緩存到內存時圖片的大小,默認是屏幕尺寸的長寬 .diskCacheExtraOptions(480, 800, null) // 指定緩存到硬盤時圖片的大小,并不建議使用 .taskExecutor(new Executor()) // 自定義一個線程來加載和顯示圖片 .taskExecutorForCachedImages(new Executor())// 自定義一個線程來緩存圖片 .threadPoolSize(3) // default, 指定線程池大小 .threadPriority(Thread.NORM_PRIORITY - 2) // default ,指定線程優先級 .tasksProcessingOrder(QueueProcessingType.FIFO) // default , 指定加載顯示圖片的任務隊列的類型 .denyCacheImageMultipleSizesInMemory() // 禁止在內存中緩存同一張圖片的多個尺寸類型 .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 指定內存緩存的大小,默認值為1/8 應用的最大可用內存 .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiskCache(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() // 是否顯示Log .build(); // ImageLoaderConfiguration 簡單初始化 ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this); // 初始化配置 ImageLoader.getInstance().init(configuration);
-
DisplayImageOptions 參數詳解:
DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) // 圖片正在加載時顯示的圖片資源ID .showImageForEmptyUri(R.drawable.ic_empty) // URI為空時顯示的圖片資源ID .showImageOnFail(R.drawable.ic_error) // 圖片加載失敗時顯示的圖片資源ID .resetViewBeforeLoading(false) // default 圖片在下載前是否重置,復位 .delayBeforeLoading(1000) // 圖片開始加載前的延時.默認是0 .cacheInMemory(false) // default , 是否緩存在內存中, 默認不緩存 .cacheOnDisk(false) // default , 是否緩存在硬盤 , 默認不緩存 .preProcessor(new BitmapProcessor) // 設置圖片緩存在內存前的圖片處理器 .postProcessor(new BitmapProcessor) // 設置圖片在緩存到內存以后 , 顯示在界面之前的圖片處理器 .extraForDownloader(...) // 為圖片下載設置輔助參數 .considerExifParams(false) // default , 設置是否考慮JPEG圖片的EXIF參數信息,默認不考慮 .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default , 指定圖片縮放的方式,ListView/GridView/Gallery推薦使用此默認值 .bitmapConfig(Bitmap.Config.ARGB_8888) // default , 指定圖片的質量,默認是 ARGB_8888 .decodingOptions(...) // 指定圖片的解碼方式 .displayer(new SimpleBitmapDisplayer()) // default , 設置圖片顯示的方式,用于自定義 .handler(new Handler()) // default ,設置圖片顯示的方式和ImageLoadingListener的監聽, 用于自定義 .build();
-
顯示圖片的方法:
ImageLoader.getInstance().loadImage(String uri, ImageLoadingListener listener) displayImage(String uri, ImageView imageView) displayImage(String uri, ImageView imageView, DisplayImageOptions options) displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener)
-
特殊用法:
-
顯示圓形圖片.使用該效果,必須顯式指定圖片的寬高
DisplayImageOptions options = new DisplayImageOptions.Builder() .displayer(new CircleBitmapDisplayer()) .build();
-
顯示圓角圖片.使用該效果,必須顯式指定圖片的寬高
DisplayImageOptions options = new DisplayImageOptions.Builder() .displayer(new RoundedBitmapDisplayer(90)) .build();
-
顯示圓角縮放圖片.使用該效果,必須顯式指定圖片的寬高
DisplayImageOptions options = new DisplayImageOptions.Builder() .displayer(new RoundedVignetteBitmapDisplayer(90,180)) .build();
-
顯示漸顯圖片
DisplayImageOptions options = new DisplayImageOptions.Builder() .displayer(new FadeInBitmapDisplayer(3000)) .build();
-
2. 圖像_Fresco
使用步驟
添加依賴: compile 'com.facebook.fresco:fresco:0.9.0+'
-
添加權限
<uses-permission android:name="android.permission.INTERNET"/>
-
在Application初始化或在Activity 的setContentView()方法之前,進行初始化
Fresco.initialize(this);
-
在布局文件中添加圖片控件.寬高必須顯示指定,否則圖片無法顯示.
<com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="200dp" android:layout_height="200dp" fresco:placeholderImage="@mipmap/ic_launcher" />
-
在Java代碼中指定圖片的路徑.顯示圖片.SimpleDraweeView接收的路徑參數為URI,所以需要一次轉換.
Uri uri = Uri.parse(URL_IMG2); SimpleDraweeView view = (SimpleDraweeView) findViewById(R.id.my_image_view); view.setImageURI(uri);
-
XML方式配置參數.除圖片地址以外,其他所有顯示選項都可以在布局文件中指定
<com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" android:layout_height="20dp" fresco:actualImageScaleType="focusCrop"http:// 圖片的縮放方式. fresco:backgroundImage="@color/blue" //背景圖.不支持縮放.XML僅能指定一張背景圖.如果使用Java代碼指定的話,可以指定多個背景,顯示方式類似FrameLayout,多個背景圖按照順序一級一級層疊上去. fresco:fadeDuration="300" // 漸顯圖片的時間 fresco:failureImage="@drawable/error" // 圖片加載失敗顯示的圖片 fresco:failureImageScaleType="centerInside" //// 圖片加載失敗顯示的圖片的縮放類型 fresco:overlayImage="@drawable/watermark" // 層疊圖,最后疊加在圖片之上.不支持縮放.XML僅能指定一張.如果使用Java代碼指定的話,可以指定多個,顯示方式類似FrameLayout,多個圖按照順序一級一級層疊上去. fresco:placeholderImage="@color/wait_color" // 圖片加載成功之前顯示的占位圖 fresco:placeholderImageScaleType="fitCenter" // 圖片加載成功之前顯示的占位圖的縮放類型 fresco:pressedStateOverlayImage="@color/red" // 設置按壓狀態下的層疊圖.不支持縮放. fresco:progressBarAutoRotateInterval="1000" // 進度條圖片旋轉顯示時長 fresco:progressBarImage="@drawable/progress_bar" // 進度條圖片 fresco:progressBarImageScaleType="centerInside" //進度條圖片的縮放類型 fresco:retryImage="@drawable/retrying" // 當圖片加載失敗的時候,顯示該圖片提示用戶點擊重新加載圖片 fresco:retryImageScaleType="centerCrop" // 提示圖片的縮放類型 fresco:roundAsCircle="false" // 顯示圓形圖片 fresco:roundBottomLeft="false" // roundedCornerRadius屬性設置后,四個角都會有圓角,如果左下角不需要設置為false. fresco:roundBottomRight="true" // roundedCornerRadius屬性設置后,四個角都會有圓角,如果右下角不需要設置為false. fresco:roundTopLeft="true" // roundedCornerRadius屬性設置后,四個角都會有圓角,如果左上角不需要設置為false. fresco:roundTopRight="false" // roundedCornerRadius屬性設置后,四個角都會有圓角,如果右上角不需要設置為false. fresco:roundWithOverlayColor="@color/corner_color" // 設置圖片圓角后空出區域的顏色.如示例圖中的紅色部分 fresco:roundedCornerRadius="1dp" // 設置圖片圓角角度,設置該屬性后四個角都會生效 fresco:roundingBorderColor="@color/border_color" // 設置圓角后,邊框的顏色. fresco:roundingBorderWidth="2dp" /> // 設置圓角后,外邊框的寬高 
-
Java代碼配置參數.
GenericDraweeHierarchy hierarchy = GenericDraweeHierarchyBuilder .newInstance(getResources()) .setRetryImage(getResources().getDrawable(R.mipmap.ic_launcher)) .build(); imageivew.setHierarchy(hierarchy);
-
特殊用法:
-
顯示漸進式JPEG圖片
ProgressiveJpegConfig pjpegConfig = new ProgressiveJpegConfig() { @Override // 返回下一個需要解碼的掃描次數 public int getNextScanNumberToDecode(int scanNumber) { return scanNumber + 2; } // 確定多少個掃描次數之后的圖片才能開始顯示 public QualityInfo getQualityInfo(int scanNumber) { boolean isGoodEnough = (scanNumber >= 5); return ImmutableQualityInfo.of(scanNumber, isGoodEnough, false); } }; // ImagePipelineConfig配置如何加載圖像 ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this) .setProgressiveJpegConfig(pjpegConfig) .build(); img_uri = Uri.parse(URL_IMG2); // 顯式地指定允許漸進式JPEG圖片加載 ImageRequest request = ImageRequestBuilder .newBuilderWithSource(img_uri) .setProgressiveRenderingEnabled(true) .build(); // 構建顯示圖片所用到的DraweeController DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(simpleDraweeView.getController()) .build(); simpleDraweeView.setController(controller);
-
顯示GIF圖片.Fresco 支持 GIF 和 WebP 格式的動畫圖片.如果你希望圖片下載完之后自動播放,同時,當View從屏幕移除時,停止播放,只需要在 image request 中簡單設置,示例代碼:
DraweeController controller = Fresco.newDraweeControllerBuilder() .setUri(URL_GIF) .setAutoPlayAnimations(true) .build(); simpleDraweeView.setController(controller);
-
3. 圖像_Picasso
- 主頁: https://github.com/square/picasso
- 使用步驟
添加依賴 compile 'com.squareup.picasso:picasso:2.5.2'
-
添加權限:
<uses-permission android:name="android.permission.INTERNET"/>
-
加載圖片,示例代碼:
Picasso .with(this)// 指定Context .load(URL_IMG3) //指定圖片URL .placeholder(R.mipmap.ic_launcher) //指定圖片未加載成功前顯示的圖片 .error(R.mipmap.ic_launcher)// 指定圖片加載失敗顯示的圖片 .resize(300, 300)// 指定圖片的尺寸 .fit()// 指定圖片縮放類型為fit .centerCrop()// 指定圖片縮放類型為centerCrop .centerInside()// 指定圖片縮放類型為centerInside .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)// 指定內存緩存策略 .priority(Picasso.Priority.HIGH)// 指定優先級 .into(imageView); // 指定顯示圖片的ImageView
-
顯示圓形圖片.示例代碼:
// 自定義Transformation Transformation transform = new Transformation() { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig()); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); paint.setShader(shader); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squaredBitmap.recycle(); return bitmap; } @Override public String key() { return "circle"; } }; Picasso .with(this)// 指定Context .load(URL_IMG2) //指定圖片URL .transform(transform) // 指定圖片轉換器 .into(imageView); // 指定顯示圖片的ImageView
-
顯示圓角圖片
class RoundedTransformation implements com.squareup.picasso.Transformation { private final int radius; private final int margin; // dp // radius is corner radii in dp // margin is the board in dp public RoundedTransformation(final int radius, final int margin) { this.radius = radius; this.margin = margin; } @Override public Bitmap transform(final Bitmap source) { final Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint); if (source != output) { source.recycle(); } return output; } @Override public String key() { return "rounded(radius=" + radius + ", margin=" + margin + ")"; } } Picasso .with(this)// 指定Context .load(URL_IMG2) //指定圖片URL .transform(new RoundedTransformation(360,0)) // 指定圖片轉換器 .into(imageView); // 指定顯示圖片的ImageView
3.4圖像_Glide
- 主頁: https://github.com/bumptech/glide
- 中文文檔: http://mrfu.me/2016/02/27/Glide_Getting_Started/
- 使用步驟
添加依賴 compile 'com.github.bumptech.glide:glide:3.7.0' , 同時還依賴于supportV4.如果沒有請自行添加
-
添加權限:
<uses-permission android:name="android.permission.INTERNET"/>
-
加載圖片.示例代碼:
Glide .with(this) // 指定Context .load(URL_GIF)// 指定圖片的URL .placeholder(R.mipmap.ic_launcher)// 指定圖片未成功加載前顯示的圖片 .error(R.mipmap.ic_launcher)// 指定圖片加載失敗顯示的圖片 .override(300, 300)//指定圖片的尺寸 .fitCenter()//指定圖片縮放類型為fitCenter .centerCrop()// 指定圖片縮放類型為centerCrop .skipMemoryCache(true)// 跳過內存緩存 .diskCacheStrategy(DiskCacheStrategy.NONE)//跳過磁盤緩存 .diskCacheStrategy(DiskCacheStrategy.SOURCE)//僅僅只緩存原來的全分辨率的圖像 .diskCacheStrategy(DiskCacheStrategy.RESULT)//僅僅緩存最終的圖像 .diskCacheStrategy(DiskCacheStrategy.ALL)//緩存所有版本的圖像 .priority(Priority.HIGH)//指定優先級.Glide 將會用他們作為一個準則,并盡可能的處理這些請求,但是它不能保證所有的圖片都會按照所要求的順序加載。優先級排序:IMMEDIATE > HIGH > NORMAL > LOW .into(imageView);//指定顯示圖片的ImageView
-
顯示圓形圖片
class GlideCircleTransform extends BitmapTransformation { public GlideCircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; // TODO this could be acquired from the pool too Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); return result; } @Override public String getId() { return getClass().getName(); } } Glide .with(this) // 指定Context .load(URL_GIF)// 指定圖片的URL .transform(new GlideCircleTransform(this)) // 指定自定義BitmapTransformation .into(imageView);//指定顯示圖片的ImageView Glide .with(context) .load("file:///android_asset/itheima.jpg") //加載assets目錄下圖片 .fitCenter() .into(holder.iv);
-
顯示圓角圖片
class GlideRoundTransform extends BitmapTransformation { private static float radius = 0f; public GlideRoundTransform(Context context) { this(context, 4); } public GlideRoundTransform(Context context, int dp) { super(context); this.radius = Resources.getSystem().getDisplayMetrics().density * dp; } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return roundCrop(pool, toTransform); } private static Bitmap roundCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight()); canvas.drawRoundRect(rectF, radius, radius, paint); return result; } @Override public String getId() { return getClass().getName() + Math.round(radius); } } Glide .with(this) // 指定Context .load(URL_GIF)// 指定圖片的URL .transform(new GlideRoundTransform(this,30)) // 指定自定義BitmapTransformation .into(imageView);//指定顯示圖片的ImageView
-
更改Glide默認配置的步驟:
-
創建一個GlideModule的實現類,并在其中更改自己需要的設置.示例代碼:
public class SimpleGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { // 更改Bitmap圖片壓縮質量為8888,默認為565 builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); } @Override public void registerComponents(Context context, Glide glide) { // todo } }
-
在manifet/Application中添加一個meta-data節點.name值為剛剛創建的GlideModule實現類的完整包名+類名,value值為GlideModule.示例代碼:
<meta-data android:name="com.alpha.glidedemo.SimpleGlideModule" android:value="GlideModule" />
之后Glide加載圖片的時候將會按照新的設置加載.
-
圖像庫對比
- 快速加載圖片推薦Glide
- 對圖片質量要求較高推薦Picasso
- 如果應用加載的圖片很多,推薦Fresco > Glide > Picasso