An overview of the

Fresco is facebook's open source library that enables more efficient loading of web and resource images. It has its own level 3 cache function, which makes the image display more efficient.Copy the code

introduce

Fresco is a powerful image-loading component. There is a module designed in Fresco called image Pipeline. It is responsible for loading images from the network, from local file systems, from local resources. To maximize space and CPU time, it includes a three-level cache design (two levels of memory, one level of files). A module called Drawees is designed in Fresco to conveniently display loading maps, freeing up memory and space when the images are no longer displayed on the screen. Fresco supports Android2.3(API level 9) and above.Copy the code

Simple to use

In short, there are only three steps.

1. Add dependencies 2. Initialize Fresco 3. Write layout 4. Specify the UriCopy the code

1. Add dependencies

In your module-level Gradle write:

The compile 'com. Facebook. Fresco ": the fresco" : 0.10.0'Copy the code

2. Initialize Fresco

In your custom application, or in the activity. onCreate method, call setContentView before:

Fresco.initialize(this);
Copy the code

3. Write the layout

Declare the namespace XMLNS: fresco “=” schemas.android.com/apk/res-aut…

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">
Copy the code

Write a SimpleDraweeView

<com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view0"
android:layout_width="200dp"
android:layout_height="200dp"
/>
Copy the code

4. Specify the Uri

final String str2 = "http://h.hiphotos.baidu.com/zhidao/pic/item/279759ee3d6d55fb65c51e786c224f4a20a4dd69.jpg";
Uri uri = Uri.parse(str2);
my_image_view0.setImageURI(uriERR);
Copy the code

Some concepts of Fresco

DraweeView

Inherit from View, responsible for the display of pictures. In general, use SimpleDraweeViewCopy the code

ImageRequest

ImageRequest stores useful information that Image Pipeline needs to process the requested Image (Uri, whether the Image is progressive, whether the thumbnail is returned, scaling, whether the rotation is automatic, etc.).Copy the code

Fresco’s requirements for layout width and height

You must declare android:layout_width and Android :layout_height. If you do not declare these two attributes in the XML, the image will not load correctly.Copy the code

Drawees does not support the WRAP_content attribute.

There are reasons to do this:

The downloaded image may not be the same size as the placeholder map, or if an error map is set or a repeat attempt is made, it may not be the same size as the downloaded image. If the size is inconsistent, assuming wrAP_content is used, after the image is downloaded, the View will be rearranged to change the size and position. This will cause the interface to jump.Copy the code

Consider that the cached image will be thumbnail based on your size, the phone’s screen will rotate and the ImageView will change size, etc., which will cause the image to not display properly.

Fixed aspect ratio

Use wrAP_content only if you want to display a fixed aspect ratio. If you want the image to be displayed at a specific aspect ratio, such as 4:3, you can specify it in the XML:

<com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" Android: layout_height = "wrap_content" fresco ": viewAspectRatio =" 1.33 "<! -- other attributes -->Copy the code

You can also specify the display scale in your code:

MSimpleDraweeView. SetAspectRatio (1.33 f);Copy the code

Specifies a placeholder picture

Use progressBarImage to specify images when loading. Use failureImage to specify images when loading. Use progressBarImage to specify placeholder images when loading

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/my_image_view0"
    android:layout_width="200dp"
    android:layout_height="200dp"
    fresco:progressBarImage="@drawable/loading"
    fresco:progressBarImageScaleType="centerInside"
    fresco:failureImage="@drawable/error2"
    fresco:failureImageScaleType="centerInside"
    fresco:actualImageScaleType="centerCrop"
    fresco:placeholderImage="@drawable/loading" />
Copy the code

In case of load failure, you can set click reload. An image is provided, and when the load fails, this image (instead of the failed image) is displayed, prompting the user to click retry. In ControllerBuilder, set the following:

.setTapToRetryEnabled(true)
Copy the code

Specify failed to load picture and click reload

Specify in XML a picture that prompts retry after a load failure

fresco:retryImage="@drawable/retrying"
fresco:retryImageScaleType="centerCrop"
Copy the code

And set this in ControllerBuilder:

.setTapToRetryEnabled(true)
Copy the code

When loading fails, the image pipeline retries four times; If the loading still fails, the loading failure prompt picture is displayed.

The rounded picture

It’s so easy to implement a rounded image, just declare on rounded corners in the XML layout and specify RADIUS. Any combination of four corners can be rounded.

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/my_image_viewRound"
    android:layout_width="200dp"
    android:layout_height="200dp"
    fresco:roundedCornerRadius="30dp"
    fresco:roundTopLeft="true"
    fresco:roundTopRight="false"
    fresco:roundBottomLeft="false"
    fresco:roundBottomRight="true"
    fresco:placeholderImage="@drawable/loading" />
Copy the code

Progressive JPEG diagrams

Fresco supports progressive JPEG images of the web. As you start loading, the image will appear from blurry to clear. You can set a definition standard that will display a placeholder map until the definition is reached. Progressive JPEG diagrams only support network diagrams

SimpleDraweeView my_image_view0 = (SimpleDraweeView) findViewById(R.id.my_image_view0); Build ImageRequest to load images

/** * demo: gradually loading the image, i.e. from blur gradually clear. */ private void showProgressiveJPEGs() {final String str3_progressive = "http://pooyak.com/p/progjpeg/jpegload.cgi?o=1"; Uri uri = Uri.parse(str3_progressive); ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .setProgressiveRenderingEnabled(true) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(my_image_view0.getController()) .build(); my_image_view0.setController(controller); }Copy the code

Animation support

Fresco supports animated images in GIF and WebP formats. Support for animated graphics in WebP format includes extended WebP format, even on Android 2.3 and later systems that do not have native WebP support.

Set the animation to play automatically

If you want the image to play automatically after downloading and stop playing when the View is removed from the screen, simply set it in the Image Request as follows:

Uri uri;
DraweeController controller = Fresco.newDraweeControllerBuilder()
    .setUri(uri)
    .setAutoPlayAnimations(true)
    .build();
mSimpleDraweeView.setController(controller);
Copy the code

Listening for download events

Sometimes we need to listen to what the picture is showing, to do something in the middle of failure, in the middle of success. 1. Specify a DraweeController for SimpleDraweeView 2. Specify a ControllerListener for DraweeController 3. Handles failures, in-between, and successes in the ControllerListener callback method

Uri uri;
DraweeController controller = Fresco.newControllerBuilder()
    .setControllerListener(controllerListener)
    .setUri(uri);
    .build();
mSimpleDraweeView.setController(controller);
Copy the code

The code above specifies a ControllerListener that contains callback methods:

OnFinalImageSet loading complete onIntermediateImageSet loading process onFailure loading failedCopy the code

Fresco provides a recommendation inheritance BaseControllerListener.

ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet(  String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) { if (imageInfo == null) { return; } QualityInfo qualityInfo = imageInfo.getQualityInfo(); FLog.d("Final image received! " + "Size %d x %d", "Quality level %d, good enough: %s, full quality: %s", imageInfo.getWidth(), imageInfo.getHeight(), qualityInfo.getQuality(), qualityInfo.isOfGoodEnoughQuality(), qualityInfo.isOfFullQuality()); } @Override public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) { FLog.d("Intermediate image received"); } @Override public void onFailure(String id, Throwable throwable) { FLog.e(getClass(), throwable, "Error loading %s", id) } };Copy the code

Fresco support for resources of various Uri types

Fresco uses a Uri object to specify the image to display.

Uri Uri = uri.parse ("res:// package name (which can be any string or even empty)/" + r.rawable.icCopy the code

Fresco supports a number of URI formats. See the table below:

Type Scheme Example Remote image: http://, https:// HttpURLConnection Or refer to other network loading schemes. Local file: file:// FileInputStream Content provider: The content: / / ContentResolver asset directory of Resources: asset: / / AssetManager res directory of Resources: res: / / Resources. OpenRawResourceCopy the code

Note that Fresco does not support urIs for relative paths. All URIs must be absolute paths with a scheme for that URI.

Extend resources

  • I wrote the demo: github.com/vir56k/demo…
  • Making: github.com/facebook/fr…
  • Chinese document: www.fresco-cn.org/