五、Fresco的使用

2019-02-05  本文已影响0人  贵翼

一、Fresco简介

1.1 Fresco是Facebook最新推出的一款用于Android应用中展示图片的强大图片库,可以从网络、本地存储和本地资源中加载图片。相对于ImageLoader,拥有更快的图片下载速度以及可以加载和显示gif图等诸多优势,是个很好的图片框架。

二、下载地址

https://github.com/facebook/fresco
官网使用地址

三、支持的URI

远程图片:http://, https://
本地文件:file://
Content provider:content://
asset目录下的资源:asset://
res目录下的资源:res://
Uri中指定图片数据:data:mime/type;base64

四、使用步骤

4.1 添加依赖

 implementation 'com.facebook.fresco:fresco:1.11.0'
 implementation 'com.facebook.fresco:animated-gif:1.11.0'//有动态图才需要添加

4.2 在application中初始化Fresco

public class Myapplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

         Fresco.initialize(this);
    }

将Myapplication 配置到清单文件中


1.png

4.3 配置网络权限

4.4 在xml布局文件中,加入命名空间

<!-- 其他元素-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">

4.5 在xml中引入SimpleDraweeView

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/my_image_view"
    android:layout_width="130dp"//必须写明是多少dp
    android:layout_height="130dp"
    fresco:placeholderImage="@drawable/my_drawable" />

4.6 在Java代码中开始加载图片

Uri uri = Uri.parse("https://raw.githubusercontent.com/facebook/fresco/gh-pages/static/logo.png");

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

draweeView.setImageURI(uri);

五、例子

5.1 带进度条的图片

  // 设置带进度条样式
        GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
        GenericDraweeHierarchy hierarchy = builder.setProgressBarImage(new ProgressBarDrawable()).build();

        sdvFresco.setHierarchy(hierarchy);

        // 加载图片地址
        Uri uri = Uri.parse("http://img4.duitang.com/uploads/item/201211/24/20121124175330_ruKEK.jpeg");

        // 设置显示图片
        sdvFresco.setImageURI(uri);

5.2 图片的不同裁剪

GenericDraweeHierarchyBuilder  builder = new GenericDraweeHierarchyBuilder(getResources());
GenericDraweeHierarchy hierarchy = builder.setActualImageScaleType(ScalingUtils.ScaleType.CENTER).build();//此处为居中无缩放显示,使用不同参数有不同效果
Uri uri = Uri.parse("http://img4q.duitang.com/uploads/item/201305/20/20130520115416_VrUUR.jpeg");
sdvFrescoCrop.setImageURI(uri);

5.3 圆形和圆角图片

设置圆形图片

uri = Uri.parse("http://img4q.duitang.com/uploads/item/201304/27/20130427043538_wAfHC.jpeg");
        builder = new GenericDraweeHierarchyBuilder(getResources());

 // 设置圆形图片
    @OnClick(R.id.bt_fresco_circle)
    void bt_fresco_circle_click(View view) {

        // 参数设置为圆形
     RoundingParams   params = RoundingParams.asCircle();
     GenericDraweeHierarchy hierarchy = builder.setRoundingParams(params).build();
     sdvFrescoCircleandcorner.setHierarchy(hierarchy);

        // 加载图片
        sdvFrescoCircleandcorner.setImageURI(uri);
    }

设置圆角图片

params = RoundingParams.fromCornersRadius(50f);//设置圆角图片
                params.setOverlayColor(getResources().getColor(android.R.color.holo_red_light));//覆盖层
                params.setBorder(getResources().getColor(android.R.color.holo_blue_light), 5);//边框
                 hierarchy = builder.setRoundingParams(params).build();

                sdvFrescoCircleandcorner.setHierarchy(hierarchy);
                sdvFrescoCircleandcorner.setImageURI(uri);

5.4 渐进式展示图片

 // 加载质量配置
        ProgressiveJpegConfig jpegConfig = new ProgressiveJpegConfig() {
            @Override
            public int getNextScanNumberToDecode(int scanNumber) {
                return scanNumber + 2;
            }

            @Override
            public QualityInfo getQualityInfo(int scanNumber) {
                boolean isGoodEnough = (scanNumber >= 5);

                return ImmutableQualityInfo.of(scanNumber, isGoodEnough, false);
            }
        };

        ImagePipelineConfig.newBuilder(this).setProgressiveJpegConfig(jpegConfig).build();
        // 获取图片URL
        Uri uri = Uri.parse("http://cdn.duitang.com/uploads/item/201303/12/20130312021353_45Qix.jpeg");

        // 获取图片请求
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri).setProgressiveRenderingEnabled(true).build();

        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setTapToRetryEnabled(true)
                .setOldController(sdvFrescoJpeg.getController())//使用oldController可以节省不必要的内存分配
                .build();

        // 设置加载的控制
        sdvFrescoJpeg.setController(draweeController);

5.5 Gif动画图片

必须额外添加一个动态图依赖,版本要与之前添加的Fresoc依赖一致

 Uri uri = Uri.parse("http://192.168.1.3:8080/test/qq.gif");

                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setUri(uri)
                        .setAutoPlayAnimations(false)
                        .setOldController(sdvFrescoGif.getController())
                        .build();

                // 设置控制器
                sdvFrescoGif.setController(controller);
                break;
            case R.id.bt_fresco_stopAnim://动画停止
              animatable =   sdvFrescoGif.getController().getAnimatable();
              if (animatable!= null && animatable.isRunning()){
                  animatable.stop();
              }
                break;
            case R.id.bt_fresco_startAnim://动画开始
                animatable = sdvFrescoGif.getController().getAnimatable();
                if (animatable != null && !animatable.isRunning()){
                    animatable.start();
                }
                break;

5.6 多图请求及图片复用

a.先显示低分辨率的图,然后是高分辨率的图

//同一张图片,不同品质的Uri
                Uri lowResUri = Uri.parse("http://192.168.1.3:8080/test/low.jpg");
                Uri highResUri = Uri.parse("http://192.168.1.3:8080/test/high.jpg");
                controller = Fresco.newDraweeControllerBuilder()
                        .setLowResImageRequest(ImageRequest.fromUri(lowResUri))
                        .setImageRequest(ImageRequest.fromUri(highResUri))
                        .setOldController(sdvFrescoMulti.getController())
                        .build();
                sdvFrescoMulti.setController(controller);

b.加载本地图片

// //将本地图片地址转换成Uri
                Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/1.png"));
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setLocalThumbnailPreviewsEnabled(true)
                        .build();
                controller = Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(sdvFrescoMulti.getController())
                        .build();
                sdvFrescoMulti.setController(controller);

c.本地图片复用

//本地图片的复用
                //在请求之前,还会去内存中请求一次图片,没有才会先去本地,最后去网络uri
                //本地准备复用图片的uri  如果本地这个图片不存在,会自动去加载下一个uri
                Uri uri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/1.png"));
                //图片的网络uri
                Uri uri2 = Uri.parse("http://192.168.1.3:8080/test/high.jpg");

                ImageRequest request1 = ImageRequest.fromUri(uri1);
                ImageRequest request2 = ImageRequest.fromUri(uri2);
                ImageRequest[] requests = {request1, request2};

                 controller = Fresco.newDraweeControllerBuilder()
                        .setFirstAvailableImageRequests(requests)
                        .setOldController(sdvFrescoMulti.getController())
                        .build();

                sdvFrescoMulti.setController(controller);

5.7 图片加载监听

//监听器代码
private ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
        @Override//完全加载图片
        public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);

            if (imageInfo == null) {
                return;
            }

            QualityInfo qualityInfo = imageInfo.getQualityInfo();

            tvFrescoListener.setText("Final image received! " +
                    "\nSize: " + imageInfo.getWidth()
                    + "x" + imageInfo.getHeight()
                    + "\nQuality level: " + qualityInfo.getQuality()
                    + "\ngood enough: " + qualityInfo.isOfGoodEnoughQuality()
                    + "\nfull quality: " + qualityInfo.isOfFullQuality());
        }

        @Override//渐进式加载图片
        public void onIntermediateImageSet(String id, ImageInfo imageInfo) {
            super.onIntermediateImageSet(id, imageInfo);

            tvFrescoListener2.setText("IntermediateImageSet image receiced");
        }

        @Override//加载图片失败
        public void onFailure(String id, Throwable throwable) {
            super.onFailure(id, throwable);

            tvFrescoListener.setText("Error loading" + id);
        }
    };

//图片监听配置
 ProgressiveJpegConfig jpegConfig = new ProgressiveJpegConfig() {
            @Override
            public int getNextScanNumberToDecode(int scanNumber) {
                return scanNumber + 2;
            }

            @Override
            public QualityInfo getQualityInfo(int scanNumber) {
                boolean isGoodEnough = (scanNumber >= 5);

                return ImmutableQualityInfo.of(scanNumber, isGoodEnough, false);
            }
        };
        ImagePipelineConfig.newBuilder(this).setProgressiveJpegConfig(jpegConfig).build();

        Uri uri = Uri.parse("http://h.hiphotos.baidu.com/zhidao/pic/item/58ee3d6d55fbb2fbac4f2af24f4a20a44723dcee.jpg");
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setProgressiveRenderingEnabled(true)
                .build();

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(sdvFrescoListener.getController())
                .setImageRequest(request)
                .setControllerListener(controllerListener)//设置监听器监听图片加载状态
                .build();
        sdvFrescoListener.setController(controller);

5.8 图片修改和旋转

修改图片在内存中的大小

 int width = 50;
 int height = 50;

        Uri uri = Uri.parse("http://c.hiphotos.baidu.com/image/pic/item/962bd40735fae6cd21a519680db30f2442a70fa1.jpg");

        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setResizeOptions(new ResizeOptions(width, height)).build();

        PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                .setOldController(sdvFrescoResize.getController())
                .setImageRequest(request)
                .build();

        sdvFrescoResize.setController(controller);

旋转

Uri uri2 = Uri.parse("http://c.hiphotos.baidu.com/image/pic/item/962bd40735fae6cd21a519680db30f2442a70fa1.jpg");

        ImageRequest request1 = ImageRequestBuilder.newBuilderWithSource(uri2)
                .setAutoRotateEnabled(true).build();

        DraweeController controller1 = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request1)
                .setOldController(sdvFrescoResize.getController()).build();

        sdvFrescoResize.setController(controller1);

5.9 为图片添加网格

Uri uri = Uri.parse("http://c.hiphotos.baidu.com/image/pic/item/962bd40735fae6cd21a519680db30f2442a70fa1.jpg");

        Postprocessor redMeshPostprocessor = new BasePostprocessor() {
            @Override
            public String getName() {
                return "redMeshPostprocessor";
            }

            //绘制红色点状网格
            @Override
            public void process(Bitmap bitmap) {

                for (int x = 0; x < bitmap.getWidth(); x += 2) {

                    for (int y = 0; y < bitmap.getHeight(); y += 2) {
                        bitmap.setPixel(x, y, Color.RED);
                    }
                }
            }
        };

        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setPostprocessor(redMeshPostprocessor)
                .build();

        PipelineDraweeController controller = (PipelineDraweeController)
                Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(sdvFrescoModify.getController())
                        .build();

        sdvFrescoModify.setController(controller);

5.10 在代码中动态添加SimpleDraweeView

SimpleDraweeView simpleDraweeView = new SimpleDraweeView(this);
        simpleDraweeView.setAspectRatio(1.0f);

        final Uri uri = Uri.parse("http://img4q.duitang.com/uploads/item/201304/27/20130427043538_wAfHC.jpeg");


        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .build();

        PipelineDraweeController controller = (PipelineDraweeController)
                Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(simpleDraweeView.getController())
                        .build();

        simpleDraweeView.setController(controller);

        llFresco.addView(simpleDraweeView);
上一篇下一篇

猜你喜欢

热点阅读