Android Common picture-loading framework
Picture loading involves the caching of pictures, the processing of pictures, the display of pictures and so on. And with the mobile phone equipment on the market, the rapid development of hardware, the picture of the demand for more and more high, a little processing will cause memory overflow problems. The common practice of many software manufacturers is to borrow a third party frame for picture loading. Open source framework source code is quite complex, but the use is simpler. Most frameworks are pretty much the same, with a slightly more cumbersome configuration, but typically only one line is used, and display methods typically provide multiple overloaded methods to support different needs. This will reduce unnecessary trouble. At the same time, the use of the third party framework is more convenient, which greatly reduces the workload and improves the development efficiency. This article mainly introduces four kinds of commonly used picture loading frame, namely fresco, Imageloader, Picasso, Glide, including their respective advantages and disadvantages, use steps and so on.
First look at Fresco, Fresco is Facebook launched the open source image caching tool, the main features include: two memory cache plus Native cache constitutes a level three cache, support streaming, can be similar to Web page blur progressive display picture, for multiple frame animation picture support better, such as Gif, WebP. It has the advantage that several other frames do not have, or are, short boards of several other frames.
Advantages:
1. Images stored anonymously in the Android system shared memory, instead of the virtual machine heap memory, the image's intermediate buffer data is also stored in the local heap memory, so the application has more memory usage, will not cause the oom because the picture loads, but also reduces the garbage collector frequently calls the recycling Bitmap the result interface cotton , higher performance.
2. Progressive loading of JPEG images, support images from blur to clear loading.
3. Pictures can be displayed at any center point in the ImageView, not just the center of the picture.
4. JPEG image Resizing is also done in native, not in the virtual machine's heap memory, but also in reducing OOM.
5. Very good support for the display of GIF pictures.
Disadvantages:
1. Large frame, affecting APK volume
2. Use more cumbersome
Use steps:
1. Introduction of Fresco, including two ways, online and offline.
Introducing the form of dependency scripting online, adding dependencies in dependencies,
Compile ' com.facebook.fresco:fresco:0.9.0 '
Introduce offline introduction, need to import more arr package, including:
Compile (name: ' drawee-0.9.0 ', ext: ' AAR ')
compile (name: ' fbcore-0.9.0 ', ext: ' AAR ')
compile (name: ' imagepipeline-0.9.0 ', ext: ' AAR ')
compile (name: ' imagepipeline-base-0.9.0 ', ext: ' AAR ')
compile files (' libs/ Bolts-android-1.1.4.jar ')
The AAR mentioned above is actually the form of the Lib module compression package, including. Class and related resource files, and the usual jar contains only. class files. When using AAR packages, you also need to come to project ' Build.gradle ' and join the Allprojects method body
allprojects {
repositories {
jcenter ()
//add begin
Flatdir {
dirs ' libs '
}
//add End
}
2. Initialization is required within the procedure entry method. Adds an initialization statement to the OnCreate method.
Fresco.initialize (context);
3. In the layout file, you need to use the picture to show the place, use it to define the control
<com.facebook.drawee.view.simpledraweeview
android:id= "@+id/iv_img"
android:layout_width= "150DP"
android:layout_height= "150DP"
android:src= "@mipmap/ic_launcher"
fresco:fadeduration= "
Fresco:roundingbordercolor= "#ccc"
fresco:roundingborderwidth= "2DP"/>
4. Set the static picture, write the following code in the code
Picture load
uri uri = Uri.parse (data.url);
Holder.ivIcon.setImageURI (URI);
5. Set up GIF pictures, write the following code in the code
Draweecontroller Gifcontroller = Fresco.newdraweecontrollerbuilder (). SetUri (URI)
. Setautoplayanimations (True). Build ();
Holder.ivIcon.setController (Gifcontroller);
Imageloader is the older frame, is the most GitHub community star of a project, can be understood as a point of praise most drops, It should be the most famous one domestic many well-known software use it including Taobao Beijing East Poly cost-effective and so on. The whole library is divided into Imageloaderengine,cache and imagedownloader,imagedecoder,bitmapdisplayer,bitmapprocessor five modules, of which Cache is divided into MemoryCache and DiskCache two parts. Simply speaking, Imageloader receives the task of loading and displaying pictures, and gives it to imageloaderengine,imageloaderengine distribution task to the specific thread pool to execute, the task through Cache and Imagedownloader Get the picture, the middle may pass bitmapprocessor and imagedecoder processing, the final conversion to bitmap to Bitmapdisplayer in Imageaware display. Characterized by stability, loading speed is moderate, the disadvantage is not to support GIF image loading, the use of a little cumbersome, and caching mechanism and HTTP is not a good combination of caching, is entirely their own set of caching mechanism. The use of simple, the framework of the GitHub home page also has a quick use of the steps, is basically in the Application class OnCreate method (the whole program at the beginning of the run once) to do a simple basic configuration, you can set up according to the needs, Lazy to set the frame also provides a default configuration, calling a method. Basically configure something similar to: Cache type Ah, cache top value Ah, load the number of pictures thread pool Ah, and so on. Also set a display configuration that is different from the basic configuration when displayed on the page. A project can be based on the need to create more than one configuration object to use, this configuration is more specific, you can set whether to use disk cache (stored in the SD card general), loading pictures when the failure to display the picture, the default picture, The color style of the picture and so on. Imageloader and Volley picture part also includes most other picture frame, basically the picture processing all is similar, the difference only lies in the partial optimization, but the optimization aspect UIL namely Universal-image-loader frame does the best, the configuration is good, is simply uses the , create a picture to load the object, and then a line of code to finish displaying the picture function. The parameter is generally the image URL and ImageView object you want to display.
Advantages:
1. Support Download Progress monitor
2. You can pause the picture loading in view scrolling, and you can pause the picture loading in the view scrolling through the Pauseonscrolllistener interface.
3. The default implementation of a variety of memory caching algorithms can configure the cache algorithm, but imageloader default implementation of a large number of caching algorithms, such as Size maximum first delete, use at least the first deletion, the least recent use, advanced first Delete, the longest time to delete.
4. Support local cache filename Rule definition
Use steps:
1. Initialize the imageloaderconfiguration in the OnCreate method in the application subclass
imageloaderconfiguration config = new Imageloaderconfiguration.builder (context)//
. ThreadPriority (thread.norm_ PRIORITY-2)//
. Denycacheimagemultiplesizesinmemory ()//.
Diskcachefilenamegenerator (new Md5filenamegenerator ())
//diskcachesize (* 1024 * 1024)/Mb
. MemoryCache (New Lrumemorycache (4 * 1024 * 102 4). Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO)//
. Writedebuglogs ()//Remove for release app
. Build ();
Initialize imageloader with configuration.
Imageloader.getinstance (). init (config);
2. In the specific place directly
Picture load
//Imageloader.getinstance (). DisplayImage (Data.url, Holder.ivicon);
displayimageoptions option = new Displayimageoptions.builder ()
. Resetviewbeforeloading (True)
. Cacheondisk ( true)
. Imagescaletype (imagescaletype.exactly).
bitmapconfig (Bitmap.Config.RGB_565)
. Considerexifparams (True)
. Displayer (new Fadeinbitmapdisplayer)
. Build ();
Imageloader.getinstance (). DisplayImage (Data.url, holder.ivicon, option);
3. Load various format pictures
String Imageuri = "yun_qi_img/"; Network Picture
String Imageuri = "File:///mnt/sdcard/image.png";//sd card picture
string Imageuri = "content://media/ EXTERNAL/AUDIO/ALBUMART/13 "; Media folder
String Imageuri = "assets://image.png";//Assets
String Imageuri = "drawable://" + r.drawable.image;/ /drawable Files
4. Provides a wealth of caching strategies
Memory cache, now let's see what memory caching policy Universal-image-loader has
1. Only use the strong reference cache
Lrumemorycache (This class is the open source framework default memory cache class, caching is the strong reference of bitmap, I will analyze this class from the source above)
2. Caching with strong references combined with weak references is
Usingfreqlimitedmemorycache (if the total number of cached pictures exceeds the limit, delete the bitmap with the least frequency)
Lrulimitedmemorycache (This is also used LRU algorithm, and Lrumemorycache is different, he caches is bitmap weak reference)
Fifolimitedmemorycache (first-out cache policy, when exceeding the set value, first delete the first to add cache bitmap)
Largestlimitedmemorycache (deletes the largest bitmap object first) when the cache limit value is exceeded
Limitedagememorycache (when bitmap is added to the cache time exceeds our set value, delete it)
3. Use only weak reference caching
Weakmemorycache (the total size of this class cache bitmap is unlimited, The only disadvantage is instability, cached images are easily recycled hard disk cache)
Filecountlimiteddisccache (You can set the number of cached pictures, when more than the set value, delete the first file added to the hard disk)
Limitedagedisccache (set file to survive for the longest time, when this value is exceeded, delete the file)
Totalsizelimiteddisccache (sets the maximum cache bitmap, when this value is exceeded, deletes the file first added to the hard disk)
Unlimiteddisccache (This cache class does not have any restrictions)
Picasso is the Square Open source project, and his leader is Jakewharton, so it is widely known. Square Company, many well-known open source is also the company ' Android-times-square,leakcanary,okhttp,retrofit '. Picasso easy to use, a line of code to complete loading pictures and shows that the frame is small. However, GIF is not supported, and it may be for the server to handle the scaling of the picture, it cached pictures are not scaled, and the default use of the argb_8888 format cache pictures, cache size. The whole library is divided into Dispatcher,requesthandler and downloader,picassodrawable modules. Dispatcher is responsible for distributing and handling Action, including commit, pause, continue, cancel, network state change, retry, and so on. Simply put, Picasso receives the task of loading and displaying pictures, creates the Request and passes it to the Dispatcher,dispatcher distribution task to the specific RequestHandler, through MemoryCache and Handler ( Data acquisition interface) Gets the picture, and the picture gets successful and is displayed to Target via picassodrawable. Note that the File system section of Data above, Picasso does not have a custom local cache interface, default to use HTTP local cache, API 9 above the use of okhttp, the following use of URLConnection, so if you need to customize the local cache requires heavy Define Downloader.
Picasso Advantages
1. With statistical monitoring function. Supports the monitoring of the use of picture caching, including cache hit ratio, used memory size, saved traffic, and so on.
2. Support Priority processing. Priority tasks are selected before each task schedule, such as when the Banner priority in the APP page is higher than Icon.
3. Support delay to picture dimension calculation complete loading
4. Support Flight mode and number of concurrent threads vary according to network type. When mobile phones switch to flight mode or network type conversion, the maximum concurrent number of threads pool is automatically adjusted, for example, WiFi maximum concurrency is 4,4g to 3,3g 2. Here Picasso determines the maximum concurrency number, rather than the CPU kernel, based on the network type.
5. "None" local cache. There is no "local cache, not to say that there is no local cache, but rather Picasso did not implement, to the Square of another network library okhttp to implement, the advantage is that you can request Response Header in the Cache-control and expired Controls the expiration time of a picture.
Use steps:
1. Import Picasso jar package, add dependencies
2. Load Picture
Picture load
picasso.with (mcontext) //Create Picasso
. Load (Data.url) //incoming path
. Fade (+)// fade effect length
. into (Holder.ivicon);//Picture loaded to that location
Glide can be said to be Picasso upgrade version, there are Picasso advantages, and support GIF image load display, picture caching will automatically scale, the default use of rgb_565 format cache picture, is Picasso cache volume half. Google introduced us to a picture loading library called Glide, the author is ' Bumptech '. The library is widely used in Google's Open-source projects, including the official app, released at the 2014 Google I/O conference. The entire library is divided into Requestmanager (Request manager), Engine (data acquisition engine), Fetcher (Data Collector), MemoryCache (memory cache), Disklrucache, transformation (image processing), Encoder (local cache storage), Registry (image type and parser configuration), Target (destination) module.
Simply speaking, Glide receives the task of loading and displaying resources, creates the Request and gives it to requestmanager,request to start Engine to the data source (through Fetcher), and gets the post transformation processing To Target. Glide relies on Disklrucache, Gifdecoder and other open source libraries to complete the local cache and Gif image decoding work.
Glide Advantages
1. Not only can you do picture caching, you can also cache media files. Glide is not only a picture cache, it supports Gif, WebP, thumbnails. Even video, so it's better to be a media cache.
2. Support Priority processing.
3. Consistent with Activity/fragment life cycle, support trimmemory. Glide maintains a requestmanager for each context, which is consistent with the activity/fragment lifecycle through Fragmenttransaction, and has a corresponding Trimmemory interface implementation to invoke.
4. Support Okhttp, volley. Glide By default URLConnection get data, can cooperate with okhttp or volley use. Actual Imageloader, Picasso also support Okhttp, volley.
5. Memory friendly. Glide's memory cache has an active design that takes data from the memory cache, unlike a general implementation using GET, but with remove, and then puts the cached data in a activeresources map with a soft reference value, and counts the number of references, When the picture is loaded, it is judged and recycled if the reference count is empty. Memory cache smaller picture, Glide to URL, view_width, view_height, screen resolution, etc. as a joint key, the processing of the picture cached in the memory cache, rather than the original image to save size and activity/fragment life cycle consistent, Support Trimmemory.
Picture defaults to use the default rgb_565 instead of argb_888, although the definition is worse, but the picture is smaller, can also be configured to argb_888.
6.Glide can expire by signature or without using the local cache support URL
Use steps
1. Import Glide jar package, add dependencies
2. Load Picture
Glide.with (Mcontext) //Create Glide
. Load (Data.url) //incoming path
. into (Holder.ivicon);//Picture loaded to that location
Thank you for reading, I hope to help you, thank you for your support for this site!