[转载]Glide

转载至:http://linanyang.com/2016/04/29/Glide/

介绍

Glide由bumptech团队开发,在2014年Google正式推出,广泛的用在Google的开源项目中,Glide与Picasso有着很高的相似度,细节上有不少的区别,Glide比Picasso加载速度快,也比Picasso需要更大的缓存空间。

导入库

dependencies 
{
     compile'com.github.bumptech.glide:glide:3.7.0'
 }

基本用法

Glide 用起来非常简单

Glide.with(context)  
     .load(http://img1.imgtn.bdimg.com/it/u=3519779342,2692245303&fm=15&gp=0.jpg")  
     .into(imageview); 

这就是加载一张图片的代码

常见设置

  • .placeholder() 占位图片
  • .error() 加载失败
  • .crossFade()淡入淡出
  • .dontAnimate()无动画效果
  • .override()调整图片大小
  • .transform()自定义图形转换
  • .skipMemoryCache(true)不做内存缓存
  • .diskCacheStrategy(DiskCacheStrategy.ALL)磁盘缓存
  • DiskCacheStrategy.ALL 缓存所有版本的图片
  • DiskCacheStrategy.NONE 不缓存任何图片
  • DiskCacheStrategy.SOURCE 只缓存全分辨率的图像
  • DiskCacheStrategy.RESULT 只缓存经过处理的图片

用法(Glide可以加载gif图片 但是会消耗太多内存 谨慎使用)

    Glide.with(mContext)
         .load(R.drawable.steven)
         .dontAnimate()
         .placeholder(R.mipmap.ic_launcher)
         .error(R.mipmap.ic_launcher)
         .diskCacheStrategy(DiskCacheStrategy.ALL)
         .transform(new BitmapRotateTransformation(mContext , 90f))  自定义将图片旋转90°
         .into(imageView);

高级用法

设置网络访问库

设置为什么网络请求库就导入什么集成包,比如okhttp需导入

  • compile 'com.github.bumptech.glide:okhttp-integration:1.4.0'

      //在Application设置Glide网络访问方式
      Glide.get(this).register(GlideUrl.class, InputStream.class,new OkHttpUrlLoader.Factory(单例一个okhttpclien对象);
      //register(Class<T> modelClass,Class<Y> resourceClass,ModelLoaderFactory<T, Y> factory)前两个参数为第三个参数的泛型
    

监听加载进度

在调用.into()方法的时候不直接设置target,而是

    Glide.with(mContext).load(urlString_net)
                        .dontAnimate()        
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .error(R.mipmap.ic_launcher)
                        .into(new GlideDrawableImageViewTarget(imageView) { //加载失败
                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
    
                            }
    
                            @Override
                            public void onLoadStarted(Drawable placeholder) {//加载开始
                                super.onLoadStarted(placeholder);
    
                            }
    
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {//加载完成
                                super.onResourceReady(resource, animation);
    
                            }
                        });

设置缓存大小及清除缓存

设置缓存大小

public class CustomGlideModule implements GlideModule {
       @Override
    public void applyOptions(Context context, GlideBuilder builder) {//应用选项

//        .setMemoryCache(MemoryCache memoryCache)   
//        .setBitmapPool(BitmapPool bitmapPool)         
//        .setDiskCache(DiskCache.Factory diskCacheFactory) 
//        .setDiskCacheService(ExecutorService service)    
//        .setResizeService(ExecutorService service)  
//        .setDecodeFormat(DecodeFormat decodeFormat) 

    builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);

    int cacheSize = 10 << 20;
    builder.setDiskCache(
            new InternalCacheDiskCacheFactory(context, cacheSize) 内部缓存
            //new ExternalCacheDiskCacheFactory(context, cacheSize) 外部缓存
    );
}

@Override
public void registerComponents(Context context, Glide glide) {//注册组件
    // nothing to do here
    }
}

在AndroidManifest创建

<meta-data
       android:name="cn.lny.glide.CustomGlideModule"
       android:value="GlideModule" />

清除缓存

//清除内存缓存
Glide.get(mContext).clearMemory();
//清除磁盘缓存
new Thread(new Runnable() {
    @Override
    public void run() {
           Glide.get(mContext).clearDiskCache();
    }

注意:清除磁盘缓存必须在子线程

图形转换

旋转

public class BitmapRotateTransformation extends BitmapTransformation {

private float rotateRotationAngle = 0f;

public BitmapRotateTransformation(Context context, float rotateRotationAngle) {
    super(context);

    this.rotateRotationAngle = rotateRotationAngle;
    }

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    Matrix matrix = new Matrix();
    matrix.postRotate(rotateRotationAngle);
    Bitmap result = Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        result.setConfig(Bitmap.Config.ARGB_8888);
    }
    return result;
    }

@Override
public String getId() {
    return getClass().getName();
    }
}

切圆角

public class BitmapCircleTransformation extends BitmapTransformation {
public BitmapCircleTransformation(Context context) {
    super(context);
}

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    return circleCrop(pool , toTransform);
}


private 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;

    //创建一个空白Bitmap,将在该Bitmap上铺设画布进行绘图
    Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_4444);
    if (result == null) {
        result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_4444);
    }

    Canvas canvas = new Canvas(result);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    //选择原图中的中心矩形,绘制在画布上
    Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
    paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
    float r = size / 2f;
    canvas.drawCircle(r, r, r, paint);
    return result;
    }

@Override
public String getId() {
    return getClass().getName();
    }
}

总结

Glide库在使用过程中内存占用低,扩展性强。无法设置加载图片的最大宽高,无法指定删除某一个图片的缓存(可以用加signature的方式试其失效并重新下载,但不可以删除)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 学习来源:郭霖大师博客地址 1、图片加载框架挺多,如Volley、Glide、Picasso、Fresco、本次是...
    子谦宝宝阅读 5,684评论 0 6
  • 一、简介 在泰国举行的谷歌开发者论坛上,谷歌为我们介绍了一个名叫Glide的图片加载库,作者是bumptech。这...
    天天大保建阅读 12,209评论 2 28
  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 7,326评论 0 13
  • 在一个 Gradle 项目中在你的 build.gradle中添加下面这行代码: 从一个 URL 中加载图片就像 ...
    A_Coder阅读 6,154评论 0 4
  • Glide 是一个 android 平台上的快速和高效的开源的多媒体资源管理库,提供 多媒体文件的压缩,内存和磁盘...
    帅气的欧巴阅读 7,675评论 1 18