GitHub: Welcome to read, star click up. Glide secondary package library source code

preface

Why do you choose Glide?

  • Glide lightweight
  • Speed is fast
  • You can automatically adapt the image at the desired resolution based on the size of the image you want to load
  • Support multiple image formats (static WebP, dynamic GIF, JPEG, JPG, PNG)
  • Support for multiple data source images (URL, drawable, SRC, File, implies, RAW)
  • Google the leading
  • Read more about my previous article: Picasso, Glide, Fresco Comparative Analysis blog.csdn.net/github_3330…

Why encapsulate it when it’s already convenient?

  • Avoid too many changes when changing frames later. If you encapsulate it, you just need to change the encapsulated method without affecting all the code.
  • The entrance is unified, and all image loading is managed in this one place, so it is clear at a glance. Even if there is any change, I only need to change this one class.
  • Although the current third-party libraries are very useful, if we use them as soon as we see them, we are likely to find a replacement library when the third-party libraries cannot meet the business needs or stop maintenance, and the workload can be seen. This is the dilemma that no package faces in cutting!
  • External performance consistent, internal flexible handling principle
  • More: How to Use Open Source projects correctly?

I met Glide

Glide configuration

Add dependencies to build.gradle:

dependencies {
  compile 'com. Making. Bumptech. Glide: glide: 3.7.0'
  compile 'com. Android. Support: support - v4:19.1.0'
}Copy the code

2, confused

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

# for DexGuard only
-keepresourcexmlelements manifest/application/meta-data@value=GlideModuleCopy the code

3. Permissions If you want to obtain pictures online or store them locally, add the following permissions:

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

Glide basic use

Glide uses a Fluent Interface. To complete a complete image loading request with Glide, you need to pass at least three parameters into its constructor, which are:

  • With (Context Context)- Context is something that many Android apis call, and Glide is no exception. Glide is very handy here. You can pass any Activity or Fragment object and it will automatically extract the context.
  • Load (String imageUrl) – This is the URL of the image you want to load. In most cases this String variable will link to a web image.
  • Into (ImageView targetImageView) – passes the image you want to parse to the ImageView to display.

example:

ImageView targetImageView = (ImageView) findViewById(R.id.imageView);
String internetUrl = "http://i.imgur.com/DvpvklR.png";

Glide
    .with(context)
    .load(internetUrl)
    .into(targetImageView);Copy the code

More Glide details can be seenGlide websiteAs well asGlide course series of articles

How to perform secondary encapsulation

Now that we understand why encapsulation and the fundamentals, we’re going to get to work.

Let’s take a look at the basic usage style after I wrap it:

ImageLoader.with(this)
    .url("http://img.yxbao.com/news/image/201703/13/7bda462477.gif")
    .placeHolder(R.mipmap.ic_launcher,false)
    .rectRoundCorner(30, R.color.colorPrimary)
    .blur(40)
    .into(iv_round);Copy the code

We’ll talk more about the use of attributes later, but let’s look at the encapsulation.

Take a look at UML first:

The user only needs to care about ImageLoader, even if the library inside the package changes and updates, because the external interface is the same. In practice, ILoader is implemented by the concrete class. Here we only encapsulate GlideLoader. In fact, all operations are implemented by the ImageLoader instruction. If you want to encapsulate other third-party libraries, you just need to implement ILoader itself to complete the methods inside.

Initialize the

    public static int CACHE_IMAGE_SIZE = 250;

    public static void init(final Context context) {
        init(context, CACHE_IMAGE_SIZE);
    }

    public static void init(final Context context, int cacheSizeInM) {
        init(context, cacheSizeInM, MemoryCategory.NORMAL);
    }

    public static void init(final Context context, int cacheSizeInM, MemoryCategory memoryCategory) {
        init(context, cacheSizeInM, memoryCategory, true);
    }

    / * * * @paramContext * @paramCacheSizeInM Glide the default maximum disk cache capacity is 250MB x @paramMemoryCategory Adjusting the size of the memory cache LOW(0.5F)/NORMAL(1F)/HIGH(1.5F); * @paramIsInternalCD true Cache the disk to the application internal directory/false Cache the disk to the external storage */
    public static void init(final Context context, int cacheSizeInM, MemoryCategory memoryCategory, boolean isInternalCD) {
        ImageLoader.context = context;
        GlobalConfig.init(context, cacheSizeInM, memoryCategory, isInternalCD);
    }Copy the code

You can see that we have provided four constructors, and the comments specify the usage and meaning of all the parameters.

In addition to initialization, we also need to override the following methods in Application:

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        // The program is executed while memory is being cleaned
        ImageLoader.trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        // Execute when memory is low
        ImageLoader.clearAllMemoryCaches();
    }Copy the code

These two methods are covered in ImageLoader below.

The class you care about – ImageLoader

ImageLoader encapsulates all the methods for the user to use. Let’s take a look at what they have:

  • Imageloader. init(Context Context) // Initialize
  • ImageLoader.trimMemory(int level);
  • ImageLoader.clearAllMemoryCaches();
  • ImageLoader.getActualLoader(); // Get the current loader
  • Imageloader. with(Context Context) // Load the image
  • ImageLoader. SaveImageIntoGallery (DownLoadImageService DownLoadImageService) / / save images into the photo gallery
  • ImageLoader. PauseRequests () / / request
  • ImageLoader. ResumeRequests () / / reply to the request (when the list on the slide, call pauseRequests () request, sliding stops, call resumeRequests () restore requests, etc.)
  • ImageLoader. ClearDiskCache () / / clear disk cache (must be in the background thread calls)
  • ImageLoader. ClearMomoryCache (View View) / / clear specify the View’s cache
  • Imageloader.clearmomory () // Clear the memory cache (must be called in the UI thread)

Github project address

Various Settings for the picture – SingleConfig

All the attributes we set for the image are written in this class. Let’s take a look at it in detail:

  • Url (String URL) / / URL
  • File (String filePath) // Loads SD card resources
  • File (file file) // Loads SD card resources
  • Res (int resId) // Load drawable resource
  • Content (String contentProvider) // Loads the contentProvider resource
  • Raw (String rawPath) // Loads raw resources
  • Implies (String assertSPath) // Load the results
  • Thumbnail (float thumbnail)// Thumbnail
  • RectRoundCorner (int rectRoundRadiusf) // The radius of the rounded corner when the shape is a rounded rectangle
  • Priority (int priority) // Priority
  • Error (int errorResId) // Error placeholder
  • AsSquare () // The shape is square
  • ColorFilter (int color) // Color filter
  • DiskCacheStrategy (diskCacheStrategy diskCacheStrategy) // diskCacheStrategy. NONE: not caching images/diskCacheStrategy. SOURCE : the cache picture source file/DiskCacheStrategy. RESULT: cache the modified pictures/DiskCacheStrategy. ALL: cache ALL of the pictures, Default ignoreCertificateVerify(Boolean ignoreCertificateVerify) // HTTPS Specifies whether to ignore verification
  • AsCircle ()// Load the circle image
  • PlaceHolder (int placeHolderResId) // placeHolder
  • Override (int oWidth, int oHeight) // Set resolution a when loading the image
  • Scale (int scaleMode) // CENTER_CROP scale the image until the height of the image is greater than or equal to the width of the ImageView, then cut off the middle display; The width or height of the image is equal to the width or height of the ImageView. Default: FIT_CENTER
  • Animate (int animationId) Introduces animation
  • Animate (Animation) Introduces Animation
  • The animate (ViewPropertyAnimation Animator animato) into the animation
  • AsBitmap (BitmapListener BitmapListener)// Use bitmap to not display to imageView
  • Into (View targetView) // Display to imageView
  • ColorFilter (int filteColor) // colorFilter
  • Blur (int blurRadius) / /
  • BrightnessFilter (float level) // Adjust image brightness
  • GrayscaleFilter () // Black and white effect
  • SwirlFilter () // swirlFilter effects
  • ToonFilter () // Canvas effect
  • SepiaFilter () // Ink painting effect
  • ContrastFilter (float constrasrLevel) // Sharpen effect
  • InvertFilter () // Film effect
  • PixelationFilter (float pixelationLevel) // Mosaic effect
  • SketchFilter () // // Sketch effect
  • VignetteFilter () // Halo effect

Github project address

Transit point – GlobalConfig

The GlobalConfig class is very simple and mainly selects Loader operations. It is used for future extension purposes. If we need to use another image-loading framework in the future, we can simply inherit ILoader and configure it in GlobalConfig.

public class GlobalConfig {
    public static void init(Context context, int cacheSizeInM, 
        getLoader().init(context, cacheSizeInM, memoryCategory, isInternalCD);

    }

    public static ILoader getLoader() {

        if (loader == null) {/ / Here is only a package glide loader =newGlideLoader(); } / / Go on to fresco or Picassoreturn loader;
    }
{Copy the code

The final implementer – GlideLoader

GlideLoader implements the ILoader interface. We don’t have to worry about this class when we use it, but it’s important to know what it does. There are two main things done in GlideLoader, one is the implementation of initialization and the other is the implementation of the exit method.

The implementation of initialization

We call it in application

 ImageLoader.init(getApplicationContext());Copy the code

The method below is eventually called, and this is where the final action is done

public class GlideLoader implements ILoader {

    / * * * @paramContext * @paramCacheSizeInM Glide the default maximum disk cache capacity is 250MB x @paramMemoryCategory Adjusting the size of the memory cache LOW(0.5F)/NORMAL(1F)/HIGH(1.5F); * @paramIsInternalCD true Cache the disk to the application internal directory/false Cache the disk to the external storage */
    @Override
    public void init(Context context, int cacheSizeInM, MemoryCategory memoryCategory, boolean isInternalCD) {
        Glide.get(context).setMemoryCategory(memoryCategory); // If you want to adjust the size of the memory cache in your application, you can do the following:
        GlideBuilder builder = new GlideBuilder(context);
        if (isInternalCD) {
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, cacheSizeInM * 1024 * 1024));
        } else {
            builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, cacheSizeInM * 1024 * 1024)); }}}Copy the code

Implementation of exit methods

Regardless of whether we end up using into () or asBitmap (), we end up calling GlideLoader’s Request () method.

The request () method is to get the DrawableTypeRequest and set it according to the configuration information in the SingleConfig.

@Override
    public void request(final SingleConfig config) {
        RequestManager requestManager = Glide.with(config.getContext());
        DrawableTypeRequest request = getDrawableTypeRequest(config, requestManager);
    }Copy the code

For example, set the picture scaling method as follows:

/ / Get the previous configuration information. int scaleMode = config.getScaleMode(a);/ / Then set request based on the configuration information. switch (scaleMode) { case ScaleMode.CENTER_CROP:
                    request.centerCrop(a);
                    break;
                case ScaleMode.FIT_CENTER:
                    request.fitCenter(a);
                    break;
                default:
                    request.fitCenter(a);
                    break;
            }Copy the code

The other methods are the same and will not be explained in detail here.

conclusion

To sum up, the main idea is to select which image loading library to use in GlobalConfig, save the user’s Settings in SingleConfig, and implement it in a specific Loader. The Glide used in this article can also add the FrescoLoader. Just implement ILoader and implement the Request () method to set it with DrawableTypeRequest.

GitHub: Welcome to read, star click up. Glide secondary package library source code

Take a look at the effect:

Here our packaging is over, you can be happy to use, welcome to put forward comments and suggestions.

Glide secondary package library source code welcome to click star

use

Add the following configuration in Gradle

compile 'com. Libin. Imageloader: imageloader: 1.0.3'Copy the code

In the Application:

    ImageLoader.init(getApplicationContext());Copy the code

To prevent oom, add the following code to clear memory:

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);

        ImageLoader.trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        ImageLoader.clearAllMemoryCaches();
    }Copy the code

confusion

Add the following to proguard-rules

-dontwarn okio.**Copy the code

Because of the specific use of the article is longer, specific how to use the detailed API introduction please move my next blog Glide two encapsulation library use

Blog.csdn.net/github_3330…

GitHub: Welcome to read, star click up. Glide secondary package library source code