Glide, glideandroid

Source: Internet
Author: User
Tags webp

Glide, glideandroid

1. Introduction
At the Google Developer Forum held in Thailand, Google introduced us to a library named Glide, written by bumptech. This library is widely used in google's open-source projects, including the official app released at the 2014 google I/O conference.
(1) Easy to use
(2) high configuration and adaptability
(3) supports common image formats. Jpg png gif webp
(4) Support for multiple data source networks, local hosts, resources, Assets, etc.
(5) the high-efficiency cache policy supports Memory and Disk image caching. The default Bitmap format uses RGB_565 to reduce Memory usage by at least half.
(6) lifecycle integration automatically manages requests based on Activity/Fragment Lifecycle
(7) efficient processing of Bitmap Using Bitmap Pool to reuse Bitmap, actively calling recycle to recycle Bitmap, reducing the pressure on the system to recycle

 

2,
Https://github.com/bumptech/glide

 

3. Functions

1) Use Glide. ()
(1) with (Context context ).
Using the Application context, Glide requests are not subject to Activity/Fragment lifecycle control.
(2) with (Activity activity ).
When Activity is used as the context, Glide requests are subject to Activity lifecycle control.
(3) with (FragmentActivity ).
Glide requests are subject to FragmentActivity lifecycle control.
(4) with (android. app. Fragment fragment ).
Glide requests are subject to Fragment lifecycle control.
(5) with (android. support. v4.app. Fragment fragment ).
Glide requests are subject to Fragment lifecycle control.


2) load () Usage
Glide can basically load any media resources that can be obtained.
SD card resources: load ("file: //" + Environment. getExternalStorageDirectory (). getPath () + "/test.jpg ")
Assets Resource: load ("file: // android_asset/f003.gif ")
Raw Resource: load ("Android. resource: // com. frank. glide/raw/raw_1 ") or load (" android. resource: // com. frank. glide/raw/"+ R. raw. raw_1)
Drawable Resource: load ("android. resource: // com. frank. glide/drawable/news ") or load (" android. resource: // com. frank. glide/drawable/"+ R. drawable. news)
ContentProvider Resource: load ("content: // media/external/images/media/139469 ")
Http Resource: load ("http://img.my.csdn.NET/uploads/201508/05/1438760757_3588.jpg ")
Https resources: load ("https://img.alicdn.com/tps/TB1uyhoMpXXXXcLXVXXXXXXXXXX-476-538.jpg_240x5000q50.jpg_.webp ")
Note:
Load is not limited to the String type
It can also be: load (Uri uri), load (File file), load (Integer resourceId), load (URL url), load (byte [] model ), load (T model), loadFromMediaStore (Uri uri ).


3) important functions:
(1) Disable memory cache:
. SkipMemoryCache (true)
(2) Clear the memory cache:
// Must be called in the UI thread
Glide. get (context). clearMemory ();
(3) Disable disk cache:
. DiskCacheStrategy (DiskCacheStrategy. NONE)
(4) Clear the disk cache:
// It must be called in the background thread. We recommend that you call clearMemory () at the same time ()
Glide. get (applicationContext). clearDiskCache ();
(5) obtain the cache size:
New getdiskcachesizetask(textviewcmd.exe cute (new File (getCacheDir (), DiskCache. Factory. DEFAULT_DISK_CACHE_DIR ));

class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long> {private final TextView resultView;public GetDiskCacheSizeTask(TextView resultView) {    this.resultView = resultView;}@Overrideprotected void onPreExecute() {    resultView.setText("Calculating...");}@Overrideprotected void onProgressUpdate(Long... values) { /* onPostExecute(values[values.length - 1]); */ }@Overrideprotected Long doInBackground(File... dirs) {    try {        long totalSize = 0;        for (File dir : dirs) {            publishProgress(totalSize);            totalSize += calculateSize(dir);        }        return totalSize;    } catch (RuntimeException ex) {        final String message = String.format("Cannot get size of %s: %s", Arrays.toString(dirs), ex);        new Handler(Looper.getMainLooper()).post(new Runnable() {            @Override            public void run() {                resultView.setText("error");                Toast.makeText(resultView.getContext(), message, Toast.LENGTH_LONG).show();            }        });    }    return 0L;}@Overrideprotected void onPostExecute(Long size) {    String sizeText = android.text.format.Formatter.formatFileSize(resultView.getContext(), size);    resultView.setText(sizeText);}private static long calculateSize(File dir) {    if (dir == null) return 0;    if (!dir.isDirectory()) return dir.length();    long result = 0;    File[] children = dir.listFiles();    if (children != null)        for (File child : children)            result += calculateSize(child);    return result;}}

(6) Priority loading sequence of specified resources:

// Preferentially load Glide. with (context ). load (heroImageUrl ). priority (Priority. HIGH ). into (imageViewHero); // loads Glide. with (context ). load (itemImageUrl ). priority (Priority. LOW ). into (imageViewItem );

(7) first display the thumbnail and then the original image:

// Use 1/10 of the source image as the thumbnail Glide. with (this ). load ("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png "). thumbnail (0.1f ). into (iv_0); // use other images as the thumbnail DrawableRequestBuilder <Integer> thumbnailRequest = Glide. with (this ). load (R. drawable. news); Glide. with (this ). load ("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png "). thumbnail (thumbnailRequest ). into (iv_0 );

(8) crop, blur, and filter images:

// Round crop Glide. with (this ). load ("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png "). bitmapTransform (new CropCircleTransformation (this )). into (iv_0); // corner processing Glide. with (this ). load ("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png "). bitmapTransform (new RoundedCornersTransformation (this, 30,0, RoundedCornersTransformation. cornerType. ALL )). into (iv_0); // grayscale processing Glide. with (this ). load ("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png "). bitmapTransform (new GrayscaleTransformation (this )). into (iv_0); // other transformations...

(9) listen on the Request status:
(10) listen on the resource download progress:


4) API method description

(1) thumbnail (float sizeMultiplier ).
Request a thumbnail of the given coefficient. If the thumbnail is loaded before the full-size graph, the thumbnail is displayed. Otherwise, the thumbnail is not displayed. The coefficient sizeMultiplier must be between (0, 1) and can be recursively called.
(2) sizeMultiplier (float sizeMultiplier ).
Set the coefficient for the Target size before loading the resource.
(3) diskCacheStrategy (DiskCacheStrategy strategy ).
Set cache policies. DiskCacheStrategy. SOURCE: cached raw data, DiskCacheStrategy. RESULT: The resource data after the cache transformation (such as scaling and cropping) is DiskCacheStrategy. NONE: no cache, DiskCacheStrategy. ALL: cache SOURC and RESULT. DiskCacheStrategy. RESULT is used by default. DiskCacheStrategy. SOURCE is used for the download only operation.
(4) priority (Priority priority ).
Specify the loading priority. The higher the priority, the higher the priority. However, it is not guaranteed that all images are loaded in order. Enumerate Priority. IMMEDIATE, Priority. HIGH, Priority. NORMAL, Priority. LOW. The default value is Priority. NORMAL.
(5) dontAnimate ().
Remove all animations.
(6) animate (int animationId ).
This animation is executed when the asynchronous loading of resources is complete.
(7) animate (ViewPropertyAnimation. Animator animator ).
This animation is executed when the asynchronous loading of resources is complete.
(8) placeholder (int resourceId ).
Set the placeholder Drawable during resource loading.
(9) placeholder (Drawable drawable ).
Set the placeholder Drawable during resource loading.
(10) fallback (int resourceId ).
Drawable to be displayed when the model is set to null. If fallback is not set, when the model is empty, the Drawable of error is displayed. If the Drawable of error is not set, the Drawable of placeholder is displayed.
(11) fallback (Drawable drawable ).
Drawable displayed when the model is set to null.
(12) error (int resourceId ).
Set the Drawable displayed when load fails.
(13) error (Drawable drawable ).
Set the Drawable displayed when load fails.
(14) listener (RequestListener <? Super ModelType, TranscodeType> requestListener ).
To listen to the Request status of a resource load, you can use two callbacks: onResourceReady (R resource, T model, Target <R> target, boolean isFromMemoryCache, boolean isFirstResource) and onException (Exception e, T model, Target & lt; R & gt; target, boolean isFirstResource), but do not use a new listener for each request. Avoid unnecessary memory requests, you can use a single instance for unified exception monitoring and handling.
(15) skipMemoryCache (boolean skip ).
Set whether to skip the memory cache, but do not guarantee it will not be cached (for example, if the request is already loading resources and does not set to skip the memory cache, the resource will be cached in the memory ).
(16) override (int width, int height ).
Reset the width and height of the Target (unit: pixel ).
(17) into (Y target ).
Set the Target to which the resource will be loaded.
(18) into (ImageView view ).
Set the ImageView to which the resource will be loaded. Cancel all the previously loaded and released resources of the ImageView.
(19) into (int width, int height ).
The width and height of resources to be loaded when the background thread loads (unit: pixel ).
(20) preload (int width, int height ).
Pre-load the resource to the cache (unit: pixel ).
(21) asBitmap ().
Whether the resource is GIF or not, it is treated as Bitmap. If it is a GIF animation, it will stop at the first frame.
(22) asGif ().
Treat resources as GifDrawable. If the resource is not GIF, the system will fail and call back. error ().

 

4. Procedure
1) Add dependency in build. gradle:
Compile 'com. github. bumptech. glide: 3.7.0'
2) If your project does not have a support-v4 library, you also need to add support-v4 dependencies:
Compile 'com. android. support: support-v4: 23.3.0'
3) If you use transform, you can add a custom transform library.
Github URL:
Https://github.com/wasabeef/glide-transformations
Add dependency:
Compile 'jp. wasabeef: glide-transformations: 2.0.1'
// If you want to use the GPU Filters
Compile 'jp. co. cyberagent. android. gpuimage: gpuimage-library: 1.3.0'

 

5. Example
1) Basic use

// (1) load the network image Glide. with (this ). load ("http://img1.imgtn.bdimg.com/it/u=2615772929,948758168&fm=21&gp=0.jpg "). into (ivGlide1); // (2) load the resource image Glide. with (this ). load (R. drawable. atguigu_logo ). into (ivGlide2); // (3) load the local image String path = Environment. getExternalStorageDirectory () + "/meinv1.jpg"; File file = new File (path); Uri uri = Uri. fromFile (file); Glide. with (this ). load (uri ). into (ivGlide3); // (4) load network gifString gifUrl = "http:// B .hiphotos.baidu.com/zhidao/pic/item/faedab64034f78f066abccc57b310a55b3191c67.jpg"; Glide. with (this ). load (gifUrl ). placeholder (R. mipmap. ic_launcher ). into (ivGlide4); // (5) load the resource gifGlide. with (this ). load (R. drawable. loading ). asGif (). placeholder (R. mipmap. ic_launcher ). into (ivGlide5); // (6) Load local gifString gifPath = Environment. getExternalStorageDirectory () + "/meinv2.jpg"; File gifFile = new File (gifPath); Glide. with (this ). load (gifFile ). placeholder (R. mipmap. ic_launcher ). into (ivGlide6); // (7) load the local small video and snapshot String videoPath = Environment. getExternalStorageDirectory () + "/video.mp4"; File videoFile = new File (videoPath); Glide. with (this ). load (Uri. fromFile (videoFile )). placeholder (R. mipmap. ic_launcher ). into (ivGlide7); // (8) set the thumbnail proportion. Then, load the thumbnail first, and then load the source image String urlPath = Environment. getExternalStorageDirectory () + "/meinv1.jpg"; Glide. with (this ). load (new File (urlPath )). thumbnail (0.1f ). centerCrop (). placeholder (R. mipmap. ic_launcher ). into (ivGlide8); // (9) first create a thumbnail object, then load the thumbnail first, then load the original image DrawableRequestBuilder thumbnailRequest = Glide. with (this ). load (new File (urlPath); Glide. with (this ). load (Uri. fromFile (videoFile )). thumbnail (thumbnailRequest ). centerCrop (). placeholder (R. mipmap. ic_launcher ). into (ivGlide9 );

  

2) load images in RecyclerView

3) Transform

6. Refer to blog
Http://blog.csdn.net/shangmingchao/article/details/51125554
Http://www.cnblogs.com/whoislcj/p/5558168.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.