Android圖片載入開源庫深度推薦,安利Fresco

戀貓de小郭發表於2016-11-16
從事Android開發的猿們,一定都經歷過對載入圖片這件事報以這個表情( ‵o′)凸,每次都被IOS的同事調侃,從最先的用Volley下載後LurCache快取,到後面開源庫Universal-Image-Loader,Picasso,Glide,Fresco,終於Android的圖片載入也迎來了春天,現在就讓我們擁抱春天,用力~(後方大波Fresco福利)。

這裡沒有廣告,這裡沒有跑分,資料對比Google一下比比皆是,額···那我說什麼好(ノಠ益ಠ)ノ彡┻━┻。
對啊,女朋友···呸呸呸,那麼就來講一講用哪些庫好(你應該已經在知道了)。劇透一下(主要推薦Fresco),劇透一下(主要推薦Fresco),劇透一下(主要推薦Fresco)~~~請看到最後好不。

1、Universal-Image-Loader

  • 1W多的star,無需置疑它的受歡迎程度,簡單易上手,小喵我第一個使用的圖片載入庫就是它,適用於所有的Imageview,結合LruCache和DiskLurCache,簡單易上手,而且能夠一定程度上的節省流量和防止OOM,但是後來···它還是OOM了-( ‵o′)凸(一定不是我自己懶得優化),而且載入的速度(不是說好的不談跑分麼)和顯示效果確實比起其他的略微不足。
補充一句:記得把初始化放到Applicant裡面,不然每次都會被清快取,載入的時候用單例。複製程式碼

2、Picasso

  • 沒用過的飄過····/(ㄒoㄒ)/~~

3、Glide

  • 這是谷歌的親孩子,自帶快取,支援GIF,WebP,縮圖,甚至是Video的第一幀,對Bitmap的複用和執行緒優化有著明顯的優勢。Glide也是支援“所有”的ImageView,使用過程中十分流暢,這裡推薦兩個庫:
  • GlidePalette 一個可以在Glide載入時很方便使用Palette的庫。
  • glide-transformations 處理各種圖片顯示效果的,先看下面的圖片。為什麼著重推薦這個,因為如果是用的是圓形的ImageView或者特殊裁剪的什麼,那麼很可能會有問題。
    什麼問題?反正大家都這麼說的<( ̄3 ̄)> ,用這庫就對了。

Android圖片載入開源庫深度推薦,安利Fresco
transformations

  • 其他需要注意的,比如不能在非主執行緒下呼叫Glide載入圖片。setTag要使用SimpleTarget或者繼承GlideModule,可以配置成OKHttp來替代請求等等等等等。

 聰明的你一定知道了,因為我要說Fresco,那麼為什麼不用Glide了呢?挺好的啊~這·····因為某次我要把通過圖片URL拿本地快取的時候,我居然找不到同步獲取的方法(ノಠ益ಠ)ノ彡┻━┻,除了非同步的回撥之外,我居然找不到····而且聽說Fresco對GIF和webp支援更好,不,我不管,我要換女朋友。

前方安利入教,Fresco大法好( ﹁ ﹁ ) ~→

4、Fresco

  • 這是一個讓人又愛又恨的圖片載入,他自帶快取,支援GIF,WebP,縮圖···對圖片的快取管理對5.0以下支援更是妥妥的,功能豐富,自帶神器,帕拉啪啦啪啦··· 可惜他只支援自己的控制元件, 可惜他只支援自己的控制元件, 可惜他只支援自己的控制元件:DraweeView,繼承了ImageView,但是和ImageView沒有什麼關係,話說到底繼承幹啥?

  • 進入正題吧,感覺我好廢話。我切換到Fresco也是下了很大的決心,因為替換ImageView是一件很痛苦的事情,特別是Fresco不支援warp_content,不過強大的功能確實很吸引,才不是因為不能解決的bug和需求呢。

1、 首先推薦 FrescoImageView ,這個庫繼承了SimpleDraweeView,封裝了需要的一些介面,讓人使用起來更方便,小喵在這基礎在做一些調整和封裝,具體看下面:

利用FrescoImageView封裝好的介面,使用起來是不是很方便啊<( ̄︶ ̄)↗

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, boolean pathIsLocal) {
    loadFrescoImage(frescoImageView, uri, defaultImg, 0, false, pathIsLocal, true, null, null);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, boolean pathIsLocal, Point showSize) {
    loadFrescoImage(frescoImageView, uri, defaultImg, 0, false, pathIsLocal, true, showSize, null);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, int radius, boolean pathIsLocal, Point showSize) {
    loadFrescoImage(frescoImageView, uri, defaultImg, radius, false, pathIsLocal, true, showSize, null);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, boolean pathIsLocal, Postprocessor postprocessor) {
    loadFrescoImage(frescoImageView, uri, defaultImg, 0, false, pathIsLocal, true, null, postprocessor);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, boolean pathIsLocal, Point point, Postprocessor postprocessor) {
    loadFrescoImage(frescoImageView, uri, defaultImg, 0, false, pathIsLocal, true, point, postprocessor);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, int radius, boolean pathIsLocal, Point point, Postprocessor postprocessor) {
    loadFrescoImage(frescoImageView, uri, defaultImg, radius, false, pathIsLocal, true, point, postprocessor);
}

public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg, int radius, boolean pathIsLocal) {
    loadFrescoImage(frescoImageView, uri, defaultImg, radius, false, pathIsLocal, true, null, null);
}

public static void loadFrescoImageCircle(FrescoImageView frescoImageView, String uri, int defaultImg, boolean pathIsLocal) {
    loadFrescoImage(frescoImageView, uri, defaultImg, 0, true, pathIsLocal, true, null, null);
}

/**
 * @param frescoImageView  
 * @param uri               URL或者本地uri
 * @param defaultImg        預設資源
 * @param radius            弧形角度
 * @param showCircle        是否顯示圓
 * @param pathIsLocal       是否載入的是本地資源
 * @param gifAnima          是否執行GIF動畫
 * @param showSize          是否修改顯示大小
 * @param postprocessor     對影象進行二次處理
 */
public static void loadFrescoImage(FrescoImageView frescoImageView, String uri, int defaultImg,
                             int radius, boolean showCircle, boolean pathIsLocal, boolean gifAnima,
                             Point showSize, Postprocessor postprocessor) {
    init(frescoImageView, radius, showCircle, gifAnima, showSize, postprocessor);
    if (pathIsLocal) {
        frescoImageView.loadLocalImage(uri, defaultImg);
    } else {
        frescoImageView.loadView(uri, defaultImg);
    }
}

private static void init(FrescoImageView frescoImageView, int radius, boolean showCircle, boolean gifAnima,
                         Point showSize, Postprocessor postprocessor) {
    frescoImageView.setAnim(gifAnima);
    frescoImageView.setCornerRadius(radius);
    frescoImageView.setFadeTime(300);
    if (showCircle)
        frescoImageView.asCircle();
    if (postprocessor != null)
        frescoImageView.setPostProcessor(postprocessor);
    if (showSize != null) {
        frescoImageView.setResize(showSize);
    }
}複製程式碼


2、 fresco-processors 這個庫做對影象的二次處理,繼承於Postprocessor ,讓我們用圖片說話:
高斯模糊,改變形狀、顏色、馬賽克無所不能。
Android圖片載入開源庫深度推薦,安利Fresco
processors

3、PhotoDraweeView 功能與丁丁大名的PhotoView一樣,支援雙擊放大,單擊返回,手動放大與縮小等,無縫接入Fresco,哎喲喂,不錯喲。

4、subsampling-scale-image-view 是不是很羨慕微博和微信載入高清長圖卻不OOM,每次都被產品還有測試說的火冒三丈,這個庫讓你高潮,它採用的是BitmapRegionDecoder的方式,分段載入顯示超長圖,拒絕OOM,而且,而且,而且支援支援支援:雙擊放大,單擊返回,手動放大等,目前只能載入本地,不怕不怕,可以下下來用快取啊:

我的邏輯是,當圖片的長度大於螢幕的2倍是就使用這個載入(寬度? i dont care)

final SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) 
final String tmpUri = list.get(position).getUri();
final Uri uri = Uri.parse((tmpUri .startsWith("http")) ? tmpUri : (tmpUri .startsWith("file://")) ? tmpUri : "file://" + tmpUri );
if (tmpUri .startsWith("http")) {
    File file = FrescoUtil.getLocalCache(uri);//Fresco的本地快取
    if (file != null && file.exists()) {
        imageView.setImage(ImageSource.uri(file.getAbsolutePath()));
    } else {
        FrescoUtil.loadImage(tmpUri , context, 0, 0, new LoadingListener() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                File file = FrescoUtil.getLocalCache(uri);
                if (file != null && file.exists()) {
                    imageView.setImage(ImageSource.uri(file.getAbsolutePath()));
                }
            }
           @Override
            public void onFail() {
            }
        });
    }
} else {
    imageView.setImage(ImageSource.uri(tmpUri .replace("file://", "")));
}複製程式碼

5、注意事項(不定時更新)

  • Fresco的初始化要寫在Applicantion裡,一定要開啟DownsampleEnabled來讓圖片壓縮,不然全圖展示超大的圖片還是會有OOM,如果用了這個,在底層Fresco就幫助你調整好了,回撥給你的圖片比例取樣後一定不會OOM(雖然可以用七牛的圖片處理),而且因為Resizing 支援JPG,所以這一定要開啟。
ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)   
.setDownsampleEnabled(true)
.build();
Fresco.initialize(this, config);複製程式碼
  • Fresco在列表載入中一定要加上Resizing 來減少記憶體的開銷,如果有必要,還可以在滑動的時候做優化處理。
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);
    switch (newState) {
        case RecyclerView.SCROLL_STATE_IDLE://停止滑動
            if (Fresco.getImagePipeline().isPaused())
                Fresco.getImagePipeline().resume();
            break;
        case RecyclerView.SCROLL_STATE_DRAGGING:
            if (preScrollState == RecyclerView.SCROLL_STATE_SETTLING) {
                //觸控滑動不需要載入
                Fresco.getImagePipeline().pause();
            } else {
                //觸控滑動需要載入
                if (Fresco.getImagePipeline().isPaused())
                    Fresco.getImagePipeline().resume();
            }
            break;
        case RecyclerView.SCROLL_STATE_SETTLING://慣性滑動
            Fresco.getImagePipeline().pause();
            break;
    }
    preScrollState = newState;
}複製程式碼
  • 不能wrap_content,5.0的過場動畫需要用到下方的配置,根據你前後的跳轉來設定
getWindow().setSharedElementEnterTransition(DraweeTransition.createTransitionSet(
        ScalingUtils.ScaleType.CENTER_CROP, ScalingUtils.ScaleType.CENTER_CROP));
getWindow().setSharedElementReturnTransition(DraweeTransition.createTransitionSet(
        ScalingUtils.ScaleType.CENTER_CROP, ScalingUtils.ScaleType.CENTER_CROP));複製程式碼
  • 不要向Fresco設定大量大尺寸的R.drawable.XX資源,因為這種類似的記憶體釋放不及時,多跳轉幾個頁面很不幸你就會有OOM的可能,這中問題主要是在於設定背景,一般的loading和fail的圖片都不會很大(要那麼大幹嘛,UI你是要打架嗎( ‵o′)凸),我們選擇是把圖片儲存到SD卡之後,載入本地圖片資源,這樣可以友好的釋放背景大圖了。

  • 獲取本地圖片和下載圖片的方法

/**

 * @param uri
 * @param context
 * @param width
 * @param height
 * @param listener
 */
public static void getImageLoading(String uri, Context context, int width, int height, final LoadingListener listener) {
    getBitmapWithProcessor(uri, context, width, height, null, listener);
}

/**
 * @param uri
 * @param context
 * @param width
 * @param height
 * @param processor 處理圖片的
 * @param listener
 */
public static void getImageLoading(final String uri, Context context, final int width, final int height,
                                          BasePostprocessor processor, final LoadingListener listener) {

    ResizeOptions resizeOptions = null;
    if (width != 0 && height != 0) {
        resizeOptions = new ResizeOptions(width, height);
    }

    ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri))
            .setProgressiveRenderingEnabled(false) //不渲染
            .setPostprocessor(processor)
            .setResizeOptions(resizeOptions)
            .build();

    ImagePipeline imagePipeline = Fresco.getImagePipeline();

    DataSource> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
    dataSource.subscribe(new BaseBitmapDataSubscriber() {
        @Override
        protected void onNewResultImpl(Bitmap bitmap) {

        }

        @Override
        protected void onFailureImpl(DataSource> dataSource) {
            listener.onFail();
        }
    }, CallerThreadExecutor.getInstance());

}

public static boolean isLocalCached(Uri uri) {
    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    DataSource<Boolean> dataSource = imagePipeline.isInDiskCache(uri);
    if (dataSource == null) {
        return false;
    }
    ImageRequest imageRequest = ImageRequest.fromUri(uri);
    CacheKey cacheKey = DefaultCacheKeyFactory.getInstance()
            .getEncodedCacheKey(imageRequest, YHApplication.get());
    BinaryResource resource = ImagePipelineFactory.getInstance()
            .getMainFileCache().getResource(cacheKey);
    return resource != null && dataSource.getResult() != null && dataSource.getResult();
}

public static File getLocalCache(Uri uri) {
    if (!isLocalCached(uri))
        return null;
    ImageRequest imageRequest = ImageRequest.fromUri(uri);
    CacheKey cacheKey = DefaultCacheKeyFactory.getInstance()
            .getEncodedCacheKey(imageRequest, YHApplication.get());
    BinaryResource resource = ImagePipelineFactory.getInstance()
            .getMainFileCache().getResource(cacheKey);
    File file = ((FileBinaryResource) resource).getFile();
    return file;
}複製程式碼


這波就沒有DEMO了,如果你們有需要我再加吧。(說的有人看一樣(ノಠ益ಠ)ノ彡┻━┻。)。

個人Github : github.com/CarGuo

Android圖片載入開源庫深度推薦,安利Fresco
就瞅你咋地

相關文章