Glide 的基本使用

发布时间:2020-07-17 06:31:16 作者:HZ90
来源:网络 阅读:749
导入引用:
项目中引入Glide 图片框架:

repositories {
  mavenCentral()
}
dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:19.1.0'
}

1. 如果你的项目使用了Volley:
    dependencies {
        compile 'com.github.bumptech.glide:volley-integration:1.3.1'
        compile 'com.mcxiaoke.volley:library:1.0.5'
    }
    
    然后在你的Application的onCreate加入
    Glide.get(this)
         .register(GlideUrl.class, InputStream.class,new VolleyUrlLoader.Factory(yourRequestQueue));

2. 如果你的项目使用OkHttp:

    dependencies {
        compile 'com.github.bumptech.glide:okhttp-integration:1.3.1'
        compile 'com.squareup.okhttp:okhttp:2.4.0'
    }
    
    然后在你的Application的onCreate加入
    Glide.get(this)
         .register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient()));
3. Glide 的使用:

    Glide.with(viewHolder.p_w_picpathView.getContext()) // 不光接受Context,还接受Activity 和 Fragment

        .load(url) // 图片的加载地址

        .diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存类型,ALL:让Glide既缓存全尺寸又缓存其他尺寸

        .error(R.drawable.ic_person)//加载失败是显示的Drawable

        .placeholder()//loading时的Drawable

        .animate()//设置load完的动画

        .centerCrop()//中心切圆, 会填满

        .fitCenter()//中心fit, 以原本图片的长宽为主

        .into(p_w_picpathView); // 显示图片的容器
4. 加载GIF图片:

    Glide.with(context)
    .load(url)
    .asGif()
    .into(p_w_picpathView)

5. 加载Bitmap:

    可以用在设大图的背景

    Bitmap theBitmap = Glide.with(context)
        .load(url)
        .asBitmap()
        .into(100, 100). // 宽、高
        .get();

6. 缩略图 Thumbnail:

    缩略图, 0.1f就是原本的十分之一

    Glide.with(context)
        .load(url)
        .thumbnail(0.1f)
        .into(p_w_picpathView)
7. 变换图片的形状:

    Glide.with(getApplicationContext())
        .load(URL)
        .transform(new CircleTransform(getApplicationContext())) // 显示为圆形图片
        .into(p_w_picpathView);

    public class CircleTransform extends BitmapTransformation {
            public CircleTransform(Context context) {
                super(context);
            }
     
            @Override
            protected Bitmap transform(BitmapPool pool, Bitmap toTransform,
                    int outWidth, int outHeight) {
                return circleCrop(pool, toTransform);
            }
     
            private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
                if (source == null)
                    return null;
     
                int size = Math.min(source.getWidth(), source.getHeight());
                int x = (source.getWidth() - size) / 2;
                int y = (source.getHeight() - size) / 2;
     
                // TODO this could be acquired from the pool too
                Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
     
                Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
                if (result == null) {
                    result = Bitmap.createBitmap(size, size,
                            Bitmap.Config.ARGB_8888);
                }
     
                Canvas canvas = new Canvas(result);
                Paint paint = new Paint();
                paint.setShader(new BitmapShader(squared,
                        BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
                paint.setAntiAlias(true);
                float r = size / 2f;
                canvas.drawCircle(r, r, r, paint);
                return result;
            }
     
            @Override
            public String getId() {
                return getClass().getName();
            }
        }
 
 加载圆形图片时,不能设置.centerCrop(),否则圆形不起作用。是不是所有的Transform都是这样,我没有测试
8. Glide的一下配置,比如图片默认的RGB_565效果,可以创建一个新的GlideModule将Bitmap格式转换到ARGB_8888:
    public class GlideConfiguration implements GlideModule {    
          
            @Override
        public void applyOptions(Context context, GlideBuilder builder) {
            // Apply options to the builder here.
    
            /**
             * Disk Cache 缓存配置
             */
            // 配置缓存大小:InternalCacheDiskCacheFactory
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, yourSizeInBytes));
            // 配置内存缓存
            builder.setDiskCache(new InternalCacheDiskCacheFactory(context, cacheDirectoryName, 
                    yourSizeInBytes));
            // 配置外部缓存
            builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, cacheDirectoryName, 
                    yourSizeInBytes));
    
            // 自定义配置
            // If you can figure out the folder without I/O:
            // Calling Context and Environment class methods usually do I/O.
            builder.setDiskCache(new DiskLruCacheFactory(getMyCacheLocationWithoutIO(), 
                    yourSizeInBytes));
    
            // In case you want to specify a cache folder ("glide"):
            builder.setDiskCache(new DiskLruCacheFactory(getMyCacheLocationWithoutIO(), "glide", 
                    yourSizeInBytes));
    
            // In case you need to query the file system while determining the folder:
            builder.setDiskCache(new DiskLruCacheFactory(new CacheDirectoryGetter() {
                @Override
                public File getCacheDirectory() {
                    return getMyCacheLocationBlockingIO();
                }
            }), yourSizeInBytes);
    
        }
    
        // 如果你要创建一个完全自定义的缓存,可以实现DiskCache.Factory接口,并且使用DiskLruCacheWrapper创建缓存位置
        builder.setDiskCache(new DiskCache.Factory() {
            @Override public DiskCache build () {
                File cacheLocation = getMyCacheLocationBlockingIO();
                cacheLocation.mkdirs();
                return DiskLruCacheWrapper.get(cacheLocation, yourSizeInBytes);
            }
        });
    
        /**
         * Memory caches and pools 配置
         */
        // Size 默认是MemorySizeCalculator控制的,可以自定义
        MemorySizeCalculator calculator = new MemorySizeCalculator(context);
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
    
        //如果你想在应用程序的某个阶段动态调整缓存内存,可以通过选择一个memorycategory通过使用setmemorycategory()
        Glide.get(context).setMemoryCategory(MemoryCategory.HIGH);
    
        // Memory Cache  可以通过setMemoryCache() 方法来设置缓存大小,或者使用自己的缓存; 
        // LruResourceCache是Glide的默认实现,可以通过构造函数自定义字节大小
        builder.setMemoryCache(newLruResourceCache(yourSizeInBytes));
    
        // Bitmap Pool 通过setBitmapPool() 设置Bitmap池的大小,LruBitmapPool是Glide的默认实现类,通过该类的构造函数更改大小
        builder.setBitmapPool(new LruBitmapPool(sizeInBytes));
    
        // Bitmap Format 通过setDecodeFormat() 方法设置设置图片质量
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
    
    
        @Override
        public void registerComponents(Context context, Glide glide) {
            // register ModelLoaders here.
        }
      }
      同时在AndroidManifest.xml中将GlideModule定义为meta-data
      meta-data android:name="com.inthecheesefactory.lab.glidepicasso.GlideConfiguration"
                android:value="GlideModule"/>
9. 特性
    你可以做到几乎和Picasso一样多的事情,代码也几乎一样。
    
    Image Resizing尺寸
    
    // Glide
    .override(300, 200);
    Center Cropping
    
    
    // Glide
    .centerCrop();
    Transforming
    
    
    // Glide
    .transform(new CircleTransform(context))
    
    设置占位图或者加载错误图:
    // Glide
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.p_w_picpathnotfound)
    
10. 混淆文件的配置
    -keepnames class com.mypackage.GlideConfiguration
    # or more generally:
    #-keep public class * implements com.bumptech.glide.module.GlideModule
    
希望对刚开始使用Glide的猿友们有所帮助,后续使用中有什么问题,我会继续添加的!


推荐阅读:
  1. Glide 缓存流程
  2. android 图片加载库 Glide 的使用介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

glide 的使用 %d

上一篇:C#防止应用多开

下一篇:linux lvm扩容磁盘大小

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》