Android picture loading frame Most fully parsed (i), glide basic usage

Source: Internet
Author: User
Tags network function

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/53759439

This article is posted in my public number, sweep the bottom of the article QR code or search Guo Lin can pay attention to, every day there are articles updated.

Now the picture loading frame on Android is very mature, from the oldest old image loading frame universalimageloader, to the later Google launched volley, then to the later emerging Army glide and Picasso, And, of course, Facebook's fresco. Each one is very stable and has a very powerful function. But their use of the scene is basically coincident, that is, we simply need to choose one to learn and use is enough, each frame to try to grasp the words are a waste of time.

In these frameworks, I have studied volley and glide more deeply, and have only basic knowledge of Universalimageloader, Picasso and fresco. In terms of ease of use, glide and Picasso should all be to win over other frameworks, both of which are too simple and useful, most of the way loading pictures is a line of code can be solved, and universalimageloader and fresco in this area slightly worse.

Then compare glide and Picasso, first of all the two frameworks are very similar in usage, but in fact they have their own characteristics. Picasso is more concise and lightweight than glide, and glide is richer than Picasso. There have been a lot of comparisons between the two frameworks, so if you want to know more, you can refer to this article.

In short, there is no best frame, only the one that best suits your own. After a lot of comparison, I decided to choose Glide to do research, and this is Google's official recommended picture loading framework.

To tell you the truth, I have been preparing for the glide article for a long time, last year was originally intended to write, but has not written. Because last year I spent most of my time writing the second line of code, I could only use fragments of time to write a blog, but the glide is far more difficult than I can grasp with the fragmentation of time. Of course, I said here is the difficulty of parsing its source code, not the use of the difficulty, glide usage is very simple. So, I think last year I did not write well glide this subject article, has been dragged to this year.

Now, I have spent a lot of effort to study the source code and various usages of glide, I believe that it can now be very well mastered, so I am ready to put my knowledge of this into a new series, to help you better learn glide. This glide series will probably have about 8 articles, expected to spend half a year to finish, will include the basic usage of glide, source parsing, advanced usage, function extension and other content, may be the most detailed glide tutorial on the Internet.

So this article is the first article in this series, let's start with the basic usage of glide.

Begin

Glide is a picture-loading framework developed by Bump Technologies, which allows us to load and display images in an extremely simple way on the Android platform.

Currently, the latest stable version of Glide is 3.7.0, although 3.8.0 has launched a preview version, but the temporary problem is more. Therefore, this series of blogs will be used glide 3.7.0 version to explain, this version of the glide is quite mature and stable.

To use glide, you first need to introduce this library into our project. Create a new Glidetest project, and then add the following dependencies to the App/build.gradle file:

{    compile ‘com.github.bumptech.glide:glide:3.7.0‘}

If you are still using eclipse, you can download the Glide jar package here.

In addition, you need to use the network function in glide, so you have to declare the network permissions in the Androidmanifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

It is that simple, and then we are free to use any of the features in glide.

Loading pictures

Now let's try to use glide to load the picture. For example, this is the address of Bing on a home page map:

http://cn.bing.com/az/hprichbg/rb/Dongdaemun_ZH-CN10736487148_1920x1080.jpg

Then we want to load this picture in the program.

So first open the project's layout file, add a button and a imageview to the layout, as follows:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Match_parent"android:layout_height="Match_parent"  Android:orientation="vertical">                <buttonandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" Android:text="Load Image"android:onclick="LoadImage" />                                    <ImageViewandroid:id="@+id/image_view"android:layout_width ="Match_parent"android:layout_height="match_parent" />                        </linearlayout>

In order for the user to click on the button to be able to display the picture on ImageView, we need to modify the code in the mainactivity as follows:

 Public  class mainactivity extends appcompatactivity {ImageView ImageView;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    ImageView = (ImageView) Findviewbyid (R.id.image_view); } Public void LoadImage(View view) {String URL ="Http://cn.bing.com/az/hprichbg/rb/Dongdaemun_ZH-CN10736487148_1920x1080.jpg"; Glide.with ( This). Load (URL). into (ImageView); }}

Yes, it's that simple. Now let's run the program with the effect as shown:

As you can see, a picture on the web has been successfully downloaded and displayed on the ImageView.

And what have we done? In fact, the core code is only this line:

Glide.with(this).load(url).into(imageView);

Do not underestimate this line of code, in fact, just this line of code, you can already do a lot of things, including loading pictures on the network, loading the phone's local pictures, loading the application resources in the image and so on.

Let's take a detailed look at this line of code.

First, call the Glide.with () method to create an instance of the loaded picture. The WITH () method can receive parameters of the context, activity, or fragment type. That is to say, we choose a very wide range, whether in the activity or fragment call with () method, you can directly pass this. What if the call is not in the activity or in the fragment? It doesn't matter, we can get the applicationcontext of the current application and pass it to the WITH () method. Note that the incoming instance of the With () method determines the life cycle of the glide load picture, and if the activity or the fragment instance is passed in, the image load will stop when the activity or fragment is destroyed. If the ApplicationContext is passed in, the image load will not stop until the application is killed.

Next, take a look at the load () method, which specifies the picture resource to be loaded. Glide supports loading a wide variety of image resources, including network pictures, local images, app resources, binary streams, URI objects, and more. So the load () method also has a number of method overloads, and you can use the load () method in addition to the one that we just used to load a string URL:

//load local picture  file File = new  File (Getexternalcachedir () +  "/image.jpg" ); Glide.with (this ). Load (file). into (ImageView); //load App resources  int  resource = r.drawable.image; Glide.with (this ). Load (Resource). into (ImageView); //load binary stream  byte  [] image = Getimagebytes (); Glide.with (this ). Load (image). into (ImageView); //load URI object  Uri Imageuri = Getimageuri (); Glide.with (this ). Load (Imageuri). into (ImageView);  

Finally look at the into () method, this method is very simple, we would like to show the picture on which ImageView, the imageview of this example can be passed in. Of course, the into () method is more than just receiving parameters of the ImageView type, but it also supports a lot of richer usage, but that's a high-level technique that we'll learn in later articles.

Then a review of the basic use of glide, in fact, is the key three-step: first with (), then load (), and finally into (). By memorizing these three steps, you have already started glide.

Occupy bitmap

Now let's learn some of the glide's extended content. In fact, the three steps we have just learned are the core of glide, and all the things we want to learn are on the basis of this three-step expansion.

Looking at the effect of just loading a web image, you'll notice that after clicking the Load Image button, you'll have to wait a little while for the image to appear. This is really easy to understand, because downloading pictures from the web is going to take time. So do we have a way to optimize the user experience? Of course, glide offers a wide variety of very rich API support, including the bitmap feature.

As the name implies, the bitmap refers to the picture in the loading process, we first display a temporary picture, and so on the image loaded out and then replaced with the image to be loaded.

Let's take a look at the use of glide as bitmap function, first I prepared a picture of loading.jpg, used as a bitmap display. Then modify the code for the Glide load section as follows:

Glide.with(this)     .load(url)     .placeholder(R.drawable.loading)     .into(imageView);

Yes, it's that simple. We just inserted a placeholder () method between the three steps, and then passed the resource ID of the placeholder picture into the method. In addition, the use of the bitmap also demonstrates the use of the vast majority of the API glide, in fact, in the load () and into () method of the connection between any of the functions you want to add.

But if you rerun the code now and click Load Image, you probably won't see the bitmap effect at all. Because Glide has a very powerful caching mechanism, we just loaded that Bing Mei picture when Glide automatically already cached it down, the next time the load will be read directly from the cache, will not go to the network download, so the speed of loading is very fast, so the bitmap may be too late to display.

So here we need to do a little bit of modification to make the bitmap have a chance to show up, the code changes as follows:

Glide.with(this)     .load(url)     .placeholder(R.drawable.loading)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .into(imageView);

As you can see, a diskcachestrategy () method is threaded and passed into the Diskcachestrategy.none parameter, which disables the glide caching function.

About Glide cache aspects we will explain in detail in the following article, here just to test the bitmap function plus an additional configuration, temporarily you just need to know that disabling the cache must be written so.

Now run the code again, as shown in the following:

As you can see, when you click on the Load Image button, a placeholder bitmap is displayed immediately, and then when the actual picture is loaded, the bitmap is replaced.

Of course, this is just one of the bitmaps, except that this load occupies a bitmap, there is an exception to the bitmap. The exception to the bitmap refers to, if because of some abnormal situation caused the picture load failure, such as mobile phone network signal is not good, this time to show this exception accounted for the bitmap.

Use of exceptions for bitmaps believe you can already guess, first prepare a error.jpg picture, and then modify the code of the Glide loading section as follows:

Glide.with(this)     .load(url)     .placeholder(R.drawable.loading)     .error(R.drawable.error)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .into(imageView);

Quite simply, here again an error () method is used to specify that the exception occupies the bitmap.

Now you can change the URL address of the image to a nonexistent picture address, or simply turn off the phone's network, and then rerun the program, as shown in the effect:

In this way, we have mastered the bitmap function provided by glide.

Specify picture format

We need to know more about glide. Another powerful feature is that glide supports the loading of GIF images. This is really awesome, because by contrast Jake Warton has made it clear that Picasso won't support the loading of GIF images.

Using glide to load GIFs does not require any extra code to write, and glide internally automatically determines the image format. For example, this is the URL address of a GIF image:

http://p1.pstatp.com/large/166200019850062839d3

All we need to do is replace the URL address in the loading image code with the address above, and now rerun the code, as shown in the following:

In other words, whether we pass in a normal picture or a GIF, glide will automatically judge it and can parse it and show it correctly.

But what if I want to specify the format of the picture? For example, I want to load this picture must be a static picture, I do not need glide automatically help me to determine whether it is static or GIF.

It is still very simple to implement this function, we just need to string up a new method as follows:

Glide.with(this)     .load(url)     .asBitmap()     .placeholder(R.drawable.loading)     .error(R.drawable.error)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .into(imageView);

As you can see, there is a Asbitmap () method appended to the load () method, which means that only static images are allowed to be loaded here, without the need for glide to automatically determine the image format.

Now run the program again, as shown in the results:

Because the Asbitmap () method is called, the GIF now does not play properly, but instead displays the picture of the first frame on the interface.

Similarly, since we can force the designation to load a static picture, we can also force the specified loading of the dynamic picture. For example, if we want to implement the ability to load dynamic images, we can write:

Glide.with(this)     .load(url)     .asGif()     .placeholder(R.drawable.loading)     .error(R.drawable.error)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .into(imageView);

Here called the Asgif () method instead of the Asbitmap () method, very well understood, I believe that I do not have to do more explanation.

So now that we've specified that only dynamic images are allowed to load, what happens if we pass in a URL address for a static picture? Try it out, change the URL address of the image to just the Bing maps, and rerun the code, as shown in the results.

Yes, if you specify that only the dynamic picture can be loaded, and the incoming picture is a Zhang Jingtu, then the result will only fail to load.

Specify picture size

In fact, using glide in most cases we don't need to specify the size of the image.

Before you learn this section, you may also need to understand the concept that it is easy to create memory waste when loading images. What do you mean, memory waste? For example, the size of a picture is 1000*1000 pixels, but our interface ImageView may only be 200*200 pixels, this time if you do not do any compression of the image directly read into memory, this is a memory waste, because the program is not used at all such a high-resolution image.

About picture compression In this regard, I have also translated an official Android article, interested friends can go to read the Android efficient loading large map, multi-figure solution, effectively avoid the program oom.

With glide, we don't have to worry about image memory waste, or even memory overflow issues. Because glide never loads the full size of a picture directly into memory, it is loaded with how much. Glide will automatically determine the size of the ImageView and then load only such a large picture pixel into memory, helping us to save on memory costs.

Of course, glide also did not use any magical magic, its internal implementation principle is actually the above article introduced in the technology, so mastered the most basic principle of implementation, you can also implement a set of such a picture compression mechanism.

It is because glide is so intelligent, so just at the beginning of the time I said, in most cases we do not need to specify the size of the picture, because glide will automatically according to the size of the ImageView to determine the size of the picture.

However, if you really have this requirement, you must assign a fixed size to the picture, and glide still supports this feature. Modify the code for the Glide load section as follows:

Glide.with(this)     .load(url)     .placeholder(R.drawable.loading)     .error(R.drawable.error)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .override(100100)     .into(imageView);

Still very simple, here the override () method is used to specify the size of a picture, that is, glide now only loads the picture into the 100*100 pixel size, not the size of your imageview.

Well, today is our first article in this glide series, and it's pretty good to have written so many things. Now you know the basic usage of glide, and of course some of the most common usage. In the next article, we will try to analyze the source code of Glide, and look at the underlying usage behind the glide, what is the magic of the operation, so that we can load the image so simple? Please look forward to it.

Follow my technical public number and have high-quality technical articles pushed every day. Pay attention to my entertainment public number, work, study tired time to relax yourself.

Sweep the QR code below to follow:

Android picture loading frame Most fully parsed (i), glide basic usage

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.