Android開源框架集合分享-圖像加載

      關於網絡加載已經寫完了,今天來給大家分享一下關於圖像加載的知識,在開發中除了請求數據怎麼顯示之外,剩下的

最大的需求應該就在圖像的顯示上了,一開始的話都是直接加載,等到寫完之後發現內存溢出,然後開始優化,進行三級緩存

包括“強弱軟虛”的引用出臺,還有高大上的算法,圖片上一般是最近最少使用算法,總而言之就是優化優化再優化,像大神的

淘寶,如果不是做圖片的加載優化,APP早都崩了。

      有人說,發明都是懶人的專利,貌似好像似乎大概就是這樣,圖片這個問題開始讓大神煩擾,於是乎各種圖片加載框架開始

出現,現在比較流行像Fresco,Glide,Picasso等框架,簡單好用,不過有興趣研究源碼還是進階的好方法啊

3、圖像展示

3.1圖像_UIL(算是使用最長的圖片框架)

主頁:https://github.com/nostra13/Android-Universal-Image-Loader

使用步驟:

1.添加依賴: 

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

2.權限申請

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

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

3.在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);

4.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();

5.顯示圖片的方法:

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)

特殊用法:

1.顯示圓形圖片.使用該效果,必須顯式指定圖片的寬高

DisplayImageOptions options = new DisplayImageOptions.Builder()

.displayer(new CircleBitmapDisplayer())

.build();

2.顯示圓角圖片.使用該效果,必須顯式指定圖片的寬高

DisplayImageOptions options = new DisplayImageOptions.Builder()

.displayer(new RoundedBitmapDisplayer(90))

.build();

3.顯示圓角縮放圖片.使用該效果,必須顯式指定圖片的寬高

DisplayImageOptions options = new DisplayImageOptions.Builder()

.displayer(new RoundedVignetteBitmapDisplayer(90,180))

.build();

4.顯示漸顯圖片

DisplayImageOptions options = new DisplayImageOptions.Builder()

.displayer(new FadeInBitmapDisplayer(3000))

.build();

上述圖片加載框架學習還可以,立項的話不太建議使用,畢竟時間太長了。

3.2圖像_Fresco(facebook出產的,算是最好的,但是配置有點麻煩)

主頁: https://github.com/facebook/fresco

中文文檔:http://fresco-cn.org/docs/index.html

使用步驟

1.添加依賴: 

compile'com.facebook.fresco:fresco:0.12.0'

2.添加權限

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

3.在Application初始化或在Activity 的setContentView()方法之前,進行初始化

Fresco.initialize(this);

還要在佈局文件中添加fresco的命名空間信息配置

xmlns:fresco="http://schemas.android.com/apk/res-auto"

4.在佈局文件中添加圖片控件.寬高必須顯示指定,否則圖片無法顯示.

android:id="@+id/my_image_view"

android:layout_width="200dp"

android:layout_height="200dp"

fresco:placeholderImage="@mipmap/ic_launcher" />

5.在Java代碼中指定圖片的路徑.顯示圖片.SimpleDraweeView接收的路徑參數爲URI,所以需要一次轉換.

Uri uri = Uri.parse(URL_IMG2);

SimpleDraweeView view = (SimpleDraweeView) findViewById(R.id.my_image_view);

view.setImageURI(uri);

6.XML方式配置參數.除圖片地址以外,其他所有顯示選項都可以在佈局文件中指定

android:id="@+id/my_image_view"

android:layout_width="20dp"

android:layout_height="20dp"

fresco:actualImageScaleType="focusCrop"// 圖片的縮放方式.

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" /> // 設置圓角後,外邊框的寬高

7.Java代碼配置參數.

GenericDraweeHierarchy hierarchy = GenericDraweeHierarchyBuilder

.newInstance(getResources())

.setRetryImage(getResources().getDrawable(R.mipmap.ic_launcher))

.build();

imageivew.setHierarchy(hierarchy);

特殊用法:

1.顯示漸進式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);

2.顯示GIF圖片.Fresco 支持 GIF 和 WebP 格式的動畫圖片.如果你希望圖片下載完之後自動播放,同時,當View從屏幕移除時,停止播放,只需要在 image request 中簡單設置,示例代碼:

DraweeController controller = Fresco.newDraweeControllerBuilder()

.setUri(URL_GIF)

.setAutoPlayAnimations(true)

.build();

simpleDraweeView.setController(controller);

3.3圖像_Picasso(square出品,必是精品)

主頁: https://github.com/square/picasso

使用步驟

1.添加依賴 

compile 'com.squareup.picasso:picasso:2.5.2'

2.添加權限:

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

3.加載圖片,示例代碼:

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

4.顯示圓形圖片.示例代碼:

// 自定義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

5.顯示圓角圖片

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);

          //可以根據需求,自己設置圖像的質量,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

使用步驟

1.添加依賴 

compile 'com.github.bumptech.glide:glide:3.7.0' 

同時還依賴於supportV4.如果沒有請自行添加

2.添加權限:

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

3.加載圖片.示例代碼:

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;

4.顯示圓形圖片

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

5.顯示圓角圖片

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默認配置的步驟:

1.創建一個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

            }

}

2.在manifet/Application中添加一個meta-data節點.name值爲剛剛創建的GlideModule實現類的完整包名+類名,value值爲GlideModule.示例代碼:

android:name="com.alpha.glidedemo.SimpleGlideModule"

android:value="GlideModule" />

3.之後Glide加載圖片的時候將會按照新的設置加載.

就幾個常用的圖片框架說一下對比。

快速加載圖片推薦   Glide

對圖片質量要求較高推薦   Picasso

如果應用加載的圖片很多,推薦  Fresco > Glide > Picasso

        以上就是關於圖片加載的框架的內容,因爲這一篇的內容確實有點複雜,所以整理的時間稍微長了一些,不過肯定會有一些失誤的

地方,權限的那個地方是手寫的,不知道爲什麼粘貼不上,不知道是什麼原因,不知道其他朋友在整理文章的時候有沒有遇見這個問題,

圖片的加載的部分算是APP佔比比較大的部分,至於框架還是看自己的需求的。網絡和圖片的加載寫完了,可以說一個程序的主體基本上

就完成了,至於 頁面特效的需求,這個倒是好說一些,不過也不盡然,無論多奇葩的需求都有可能出現。

上面的資料大部分都是實踐過的,如果有什麼不對的地方,請各位朋友及時的指出來。

簡書地址:https://www.jianshu.com/p/29f101f13972

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章