Android DevandnroidAndroid UI相关

Android图片加载开源库深度推荐,安利Fresco

2016-11-15  本文已影响6581人  恋猫月亮
从事Android开发的猿们,一定都经历过对加载图片这件事报以这个表情( ‵o′)凸,每次都被IOS的同事调侃,从最先的用Volley下载后LurCache缓存,到后面开源库Universal-Image-Loader,Picasso,Glide,Fresco,终于Android的图片加载也迎来了春天,现在就让我们拥抱春天,用力~(后方大波Fresco福利)。

</p>
这里没有广告,这里没有跑分,数据对比Google一下比比皆是,额···那我说什么好(ノಠ益ಠ)ノ彡┻━┻。
对啊,女朋友···呸呸呸,那么就来讲一讲用哪些库好(你应该已经在知道了)。剧透一下(主要推荐Fresco),剧透一下(主要推荐Fresco),剧透一下(主要推荐Fresco)~~~请看到最后好不。

1、Universal-Image-Loader

补充一句:记得把初始化放到Applicant里面,不然每次都会被清缓存,加载的时候用单例。

2、Picasso

3、Glide

transformations

聪明的你一定知道了,因为我要说Fresco,那么为什么不用Glide了呢?挺好的啊~这·····因为某次我要把通过图片URL拿本地缓存的时候,我居然找不到同步获取的方法(ノಠ益ಠ)ノ彡┻━┻,除了异步的回调之外,我居然找不到····而且听说Fresco对GIF和webp支持更好,不,我不管,我要换女朋友。

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

</p>

4、Fresco

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 ,让我们用图片说话:
高斯模糊,改变形状、颜色、马赛克无所不能。

fresco-processors

3、PhotoDraweeView 功能与丁丁大名的PhotoView一样,支持双击放大,单击返回,手动放大与缩小等,无缝接入Fresco,哎哟喂,不错哟。

4、<a href="">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、注意事项(不定时更新)

</p>

ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)   
.setDownsampleEnabled(true)
.build();
Fresco.initialize(this, config);
@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;
}
getWindow().setSharedElementEnterTransition(DraweeTransition.createTransitionSet(
        ScalingUtils.ScaleType.CENTER_CROP, ScalingUtils.ScaleType.CENTER_CROP));
getWindow().setSharedElementReturnTransition(DraweeTransition.createTransitionSet(
        ScalingUtils.ScaleType.CENTER_CROP, ScalingUtils.ScaleType.CENTER_CROP));

/**

 * @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<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
    dataSource.subscribe(new BaseBitmapDataSubscriber() {
        @Override
        protected void onNewResultImpl(Bitmap bitmap) {
      
        }

        @Override
        protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> 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 : https://github.com/CarGuo

2016-11-16晚上含泪补上DEMO: https://github.com/CarGuo/FrescoUtils

就瞅你咋地
上一篇 下一篇

猜你喜欢

热点阅读