Glide 4 basic use

This is the introduction of Chinese Glide v4: Click to open the link


1. Basic use

        Glide.with(this).load("http://guolin.tech/book.png").into(iv);


2. Occupation map

RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_launcher);

        Glide.with(this).load("http://guolin.tech/book.png")
                .apply(options).into(iv);

Images that appear when the network is loaded

3. Specify picture size

RequestOptions options = new RequestOptions()
                .override(120,30);
        Glide.with(this).load("http://guolin.tech/book.png")
                .apply(options).into(iv);


override the first parameter multiplied by the second parameter represents the size. This is not recommended because the setting is too large

4. Caching mechanism

        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_launcher)
                //Exception bitmap (image that appears when loading exception)
                .error(R.mipmap.ic_launcher)
                //Disable Glide hard disk cache
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(this).load("http://guolin.tech/book.png")
                .apply(options).into(iv);

        //Glide is divided into memory cache and hard disk cache
        //Memory cache: the main function of memory cache is to prevent applications from repeatedly reading image data into memory
        //Hard disk cache: the main function of hard disk cache is to prevent applications from repeatedly downloading and reading data from the network or other places

        //Memory cache
        //You know, by default, Glide automatically turns on memory caching.
        // In other words, when we use Glide to load an image, the image will be cached in memory,
        // As long as it is not cleared from memory, the next time you use Glide to load this image, it will be read directly from memory,
        // Instead of reading from the network or hard disk again, the loading efficiency of pictures can be greatly improved.
        // Let's say you slide up and down in a recycler view,
        // Any image loaded by Glide in RecyclerView can be read and displayed directly from memory,
        // This greatly improves the user experience.

        //Memory cache is enabled by Glide by default
        //If you want to disable memory caching for some special reasons
//        RequestOptions options = new RequestOptions()
//            .skipMemoryCache(true);
        //Where setting true disables memory caching


        //Hard disk cache
        //Disable hard disk caching at the beginning of 4
        //Five parameters of diskCacheStrategy()
        //DiskCacheStrategy.NONE: indicates that nothing is cached.
        //DiskCacheStrategy.DATA: indicates that only the original image is cached.
        //DiskCacheStrategy.RESOURCE: indicates that only converted pictures are cached.
        //DiskCacheStrategy.ALL: indicates to cache both the original image and the converted image.
        //DiskCacheStrategy.AUTOMATIC: it means that Glide can intelligently choose which caching strategy to use according to the picture resources (the default option).

5. Specify the loading format

//        Automatically determine image format
        Glide.with(this).load("http://guolin.tech/test.gif").into(iv);

//        Specify picture format
        Glide.with(this)
                //This method means that only static images are allowed to load here
                //Show the first frame if it's in Gif format
                //Glide 4 has four kinds of asBitmap asDrawable asFile asGif
                .asBitmap()
                .load("http://guolin.tech/test.gif").into(iv);


6. Callback and monitoring

 //The into() method does not have to pass in ImageView only. SimpleTarget is required

        SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv.setImageDrawable(resource);
            }
        };

        Glide.with(this).load("http://guolin.tech/book.png").into(simpleTarget);

        //Here we create an instance of SimpleTarget and specify that its generic type is Drawable,
        // Then override the onresourceready () method. In the onResourceReady() method,
        // We can get the image object loaded by Glide, that is, the Drawable object passed from the method parameter.
        // With this object, you can use it for any logical operation. Here I simply display it on the ImageView.
        //The SimpleTarget implementation is created, so you only need to pass it into the into() method when loading the image.



7. Preloading

//Preload

        //Pre load before
        Glide.with(this).load("http://guolin.tech/book.png")
                .preload();
        //Call directly when you want to use it
        Glide.with(this).load("http://guolin.tech/book.png")
                .into(iv);


8. submit() method to download pictures

new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    final Context context = getApplicationContext();
                    FutureTarget<File> target = Glide.with(context)
                            .asFile().load("http://guolin.tech/book.png")
                            .submit();
                    final File imageFile = target.get();
                    //In the main thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //Route
                            LogUtil.fussenLog().d(imageFile.getParent());
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }).start();


9. listener() method listens to Glide's loading picture status

Glide.with(this)
                .load("http://www.guolin.tech/book.png")
                .listener(new RequestListener<Drawable>() {

                    //Return false to indicate that the event has not been processed and will continue to be passed down,
                    // Return true to indicate that the event has been processed and will not be passed down.
                    // For a simple example, if we use the onResourceReady() method of RequestListener
                    // If true is returned in, the onResourceReady() method of Target will not be called back.

                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        //The onLoadFailed() method will be called back when the image fails to load
                        //Judged by GlideException
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        //When the image is loaded, the onResourceReady() method will be called back
                        return false;
                    }
                })
                .into(iv);



10. Image transformation (deformation)

RequestOptions options = new RequestOptions()
                //Turn round
//                .circleCrop();

                //To become other, you need to add another dependency
                //compile 'jp.wasabeef:glide-transformations:3.0.1'

                //vague
//                .transform(new BlurTransformation());
                //black and white
                .transform(new GrayscaleTransformation());



        Glide.with(this).load("http://www.guolin.tech/book.png")
                .apply(options).into(iv);


11. Glide saves pictures locally

private void downLoadImageNew() {

        final Context context = getApplicationContext();

        RequestOptions options = new RequestOptions()
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL); //Specify picture size (original)

        Glide.with(context).asBitmap().load("http://www.guolin.tech/book.png").apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {

                        Bitmap tempBitmip = resource;
                        //Convert timestamps to fixed format
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date date = new Date(System.currentTimeMillis());
                        //Picture name
                        String mFileName = "/bzf/" + format.format(date) + ".jpg";
                        //Picture path
                        File tempPath = Environment.getExternalStorageDirectory();
                        //Save picture
                        File newFile = saveBitmap(tempPath, mFileName, tempBitmip);
                        String backgroundPath = newFile.getPath();
                        if (backgroundPath != null) {

                            // Next, insert the file into the system library
                            try {
                                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                        newFile.getAbsolutePath(), backgroundPath, null);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            // Finally inform the library to update
                            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    Uri.fromFile(new File(newFile.getPath()))));

                            Toast.makeText(context, "Picture saved to:/storage/emulated/0/bzf", Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(context, "Save failed", Toast.LENGTH_SHORT).show();
                        }



                    }
                });


-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
OK. I feel that these are enough for the time being. I will update the new ones next time.


Tags: network

Posted on Thu, 30 Apr 2020 12:11:09 -0700 by ghostrider1