Used to prepare

Add the dependent

implementation 'com. Making. Bumptech. Glide: glide: 4.8.0'
annotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.8.0'
Copy the code

permissions

<uses-permission android:name="android.permission.INTERNET"/ > <! -- Optional --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Copy the code

ACCESS_NETWORK_STATE is not required for Glide load urls, but it will help Glide handle Flaky networks and flight patterns. Glide automatically helps you with patchy network connections if you are loading images from urls: It listens for the user’s connection status and restarts requests that failed before the user reconnects to the network. If Glide detects that your application has ACCESS_NETWORK_STATE, Glide will automatically listen for connection status without additional changes

If you want to use ExternalPreferredCacheDiskCacheFactory to Glide cache storage to the public on the SD card, you will need to add WRITE_EXTERNAL_STORAGE permission.

confusion

-dontwarn com.bumptech.glide.** -keep class com.bumptech.glide.**{*; } -keep public class * implements com.bumptech.glide.module.GlideModule -keep public class * extends com.bumptech.glide.AppGlideModule -keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** { **[]$VALUES;
  public *;
}
Copy the code

Kotlin

If you use Glide annotation in a class written by Kotlin, you need to introduce a Kapt dependency instead of the regular annotationProcessor dependency:

dependencies {
  kapt 'com. Making. Bumptech. Glide: the compiler: 4.8.0'
}
Copy the code

You also need to include kotlin-kapt in your build.gradle file: apply plugin: ‘kotlin-kapt’

RequestBuilder

The RequestBuilder is the skeleton of a request in Glide that takes the requested URL and your setup items to start a new load process. The source of the RequestBuilder is as follows:

RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).asDrawable();
RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).load("url");
RequestBuilder<Bitmap> requestBuilder = Glide.with(fragment).asBitmap();
RequestBuilder<GifDrawable> requestBuilder = Glide.with(fragment).asGif();
RequestBuilder<File> requestBuilder = Glide.with(fragment).asFile();
Copy the code

use

 Glide.with(this)
    .load("url")
    .apply()// Set request options
    .transition()// Set the transition
    .thumbnail()// Slightly indent graph correlation
    .error()// Request error relatedThe listener or addListener ()/ / to monitorInto () or submit ()// Specify the target
Copy the code

RequestOptions

RequestOptions cropOptions = new RequestOptions().centerCrop();
Glide.with(fragment)
    .load(url)
    .apply(cropOptions)
    .into(imageView);
Copy the code

RequestOptions is used to provide separate options to customize Glide loading. Because the apply() method can be called multiple times, RequestOption can be used in combination. If there are conflicting Settings between RequestOptions objects, only the last RequestOptions applied will take effect.

Common apis are as follows:

Placeholder figure

Placeholders are the Drawable that is displayed while the request is being executed. When the request completes successfully, the placeholder is replaced by the requested resource

  • Placeholder (): placeholder, which will be displayed continuously if the request fails and the error Drawable is not set
  • Error (): Exception placeholder map, displayed when a request fails permanently
  • Fallback: Fallback callback, displayed if the requested URL is null

The primary purpose of a Fallback Drawable is to allow the user to indicate whether NULL is an acceptable normal condition. For example, a null profile URL might imply that the user has no profile picture set and should therefore use the default profile picture. However, NULL can also indicate that the metadata is not valid at all, or is not reachable. Glide handles NULL as an error by default, so applications that accept NULL should explicitly set a fallback Drawable.

//placeholder()
Glide.with(fragment)
  .load(url)
  .placeholder(R.drawable.placeholder)
//.placeholder(new ColorDrawable(Color.BLACK))
  .into(view);

//error()
Glide.with(fragment)
  .load(url)
  .error(R.drawable.error)
//.error(new ColorDrawable(Color.RED))
  .into(view);

//fallback
Glide.with(fragment)
  .load(url)
  .fallback(R.drawable.fallback)
//.fallback(new ColorDrawable(Color.GREY))
  .into(view);
Copy the code

Note:

  • Placeholders are loaded from Android Resources in the main thread
  • Transformations are not applied to placeholders
  • The same stateless Drawable can be used on multiple different views; Stateful drawables are different, however, and displaying them on multiple views at the same time is usually not very safe because multiple views will instantly mutate their drawables. For stateful Drawable, it is recommended to pass in a resource ID, or use newDrawable() to pass in a new copy for each request.

diskCacheStrategy()

To set the hard disk cache, the options are as follows:

  • Diskcachestrategy. NONE: indicates that no content is cached.
  • Diskcachestrategy. DATA: indicates that only raw images are cached.
  • DiskCacheStrategy. RESOURCE: said only cache the image after the transformation.
  • Diskcachestrategy. ALL: caching both the original image and the converted image.
  • DiskCacheStrategy. AUTOMATIC: let the Glide according to image resources intelligently choose to use which kind of caching strategy (the default option)

skipMemoryCache(boolean)

  • True: memory cache is skipped
  • False: do not skip memory cache

transform

The default transformation

  • CenterCrop () : The goal is to fill the entire control, scale equally, and crop when you exceed the control (width and height should be filled, so any image with a different aspect ratio will be cropped)
  • CenterInside () : The goal is to display the image completely, without clipping. When the image is not displayed, it will be scaled, but not scaled when it can be displayed
  • FitCenter () : Fill the full screen with images in their original aspect ratio
  • CircleCrop (): circular clipping
  • Transform (): Sets custom image transform

OptionalCenterCrop (), optionalCenterInside(), optionalFitCenter(), and optionalCircleCrop() with centerCrop(), The difference between centerInside(), fitCenter(), and circleCrop() : centerCrop() will throw an exception when it transforms an image of an unknown type, while optionalCenterCrop() ignores an unknown image type.

multi

transform(new MultiTransformation<>(new CenterCrop(),new CircleCrop()))
transforms(new CenterCrop(),new CircleCrop())
Copy the code

The order in which transformation parameters are passed determines the order in which these transformations are applied

Custom transform

The custom Transformation needs to inherit BitmapTransformation(or can inherit Transformation), and rewrite the following method:

equals
hashCode
updateDiskCacheKey
transform
Copy the code

Here is the CircleCrop source code

public class CircleCrop extends BitmapTransformation {
  private static final int VERSION = 1;
  private static final String ID = "com.bumptech.glide.load.resource.bitmap.CircleCrop." + VERSION;
  private static final byte[] ID_BYTES = ID.getBytes(CHARSET);

  // Bitmap doesn't implement equals, so == and .equals are equivalent here.
  @SuppressWarnings("PMD.CompareObjectsWithEquals")
  @Override
  protected Bitmap transform(
      @NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
    return TransformationUtils.circleCrop(pool, toTransform, outWidth, outHeight);
  }

  @Override
  public boolean equals(Object o) {
    return o instanceof CircleCrop;
  }

  @Override
  public int hashCode(a) {
    return ID.hashCode();
  }

  @Override
  public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) { messageDigest.update(ID_BYTES); }}Copy the code

Glide – Doubling is a perfect library to make custom transformations

override()

SIZE_ORIGINAL is used to specify the size of an image (in px). You can use target. SIZE_ORIGINAL to specify the original size of an image, but this will incur an OOM risk.

TransitionOptions

TransitionOptions is used to determine what happens between the placeholder and the target when your load is complete.

Unlike Glide V3, Glide V4 will not apply cross fades or any other transition effects by default. Transitions must be applied manually on each request.

Glide.with(this)
    .load("")
    .transition(DrawableTransitionOptions.withCrossFade())
    .into(imageView);
Copy the code
  • GenericTransitionOptions: GenericTransitionOptions
  • Call the DrawableTransitionOptions: only applies to GlideasDrawable()(default) method
  • BitmapTransitionOptions: Applies only to Glide callsasBitmap()Method

Glide in the transition of the fading effect, only is called DrawableTransitionOptions or BitmapTransitionOptions withCrossFade () method, if you need a custom transition effect, Is necessary to realize TransitionFactory, and use DrawableTransitionOptions or BitmapTransitionOptions with ways to apply your custom TransitionFactory to load.

Slightly thumbnail (thumbnail)

The //thumbnail() method makes it easy and quick to load a low resolution version of the image while loading a lossless version of the image
Glide.with(this)
    .asDrawable()
    .load("url")
    .thumbnail(Glide.with(this).load("thumbnailUrl"))
    .into(imageView);
// Load the same image with a percentage size of View or Target (0.25 here)
Glide.with(this)
    .asDrawable()
    .load("url")
    .thumbnail(0.25 f)
    .into(imageView);
Copy the code

error

Glide.with(fragment)
  .load("url")
  .error(Glide.with(fragment)
      .load("errorUrl"))
  .into(imageView);
Copy the code

Start a new request on failure. If the main request completes successfully, the error request will not be started. If you specify both a thumbnail() and an error request, the backup error request will be launched if the main request fails, even if the thumbnail request succeeds.

The listener and addListener

Glide.with(this)
    .load("url")
    .listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
            return false;
        }
    })
    .into(imageView);
Copy the code

RequestListener needs to implement two methods, one onResourceReady() and one onLoadFailed(). The onResourceReady() method is called when the image load is complete and onLoadFailed() is called when the image load fails. The onResourceReady() and onLoadFailed() methods both have a Boolean return value, false to indicate that the event has not been handled and will continue to be passed down, and true to indicate that the event has been handled and will not continue to be passed down.

Glide’s addListener method is similar to the addListener method. The difference is that when more than one Listener method is called, only the last listener callback is called. The addListener method, in turn, calls multiple callbacks set by addListener.

Into and summit

  • Into (): Downloads the image and loads the resource to the specified destination
  • Submit (): only downloads images, not loads them

Calling the Submit () method immediately returns a FutureTarget object, and Glide begins downloading the image file in the background. We then call FutureTarget’s get() method to retrieve the downloaded image file. Note that the get() method blocks the current thread until the download is complete

reference

  • Glide Chinese Course
  • RequestOptions document
  • Glide official DOCE document