一般使用
加载方式
- 从资源加载
 
    int resourceId = R.mipmap.ic_launcher;
    Glide.with(context)
         .load(resourceId)
         .into(imageViewResource);
- 从文件加载
 
//这个文件可能不存在于你的设备中。然而你可以用任何文件路径,去指定一个图片路径。
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Running.jpg");
    Glide.with(context)
          .load(file)
          .into(imageViewFile);
- 从Uri加载
 
一个工具类, 转换Uri
public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FOREWARD_SLASH = "/";
private static Uri resourceIdToUri(Context context, int resourceId) { 
        return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FOREWARD_SLASH + resourceId);
}
占位符
.error():当load()的图片不能被加载就会显示里面资源的内容.crossFade():3.6.1默认激活,默认时间为300ms,也可以用.crossFade(int duration)来自定义时间值.dontAnimate():顾名思义,不要动画
调整图片大小
override(int width, int height):可为ImageView提供精确的尺寸- 裁剪,缩放:.centerCrop(),.fitCenter()
加载Gif- 用法
 String gifUrl = "http://i.kinja-img.com/gawker-media/image/upload/s--B7tUiM5l--/gf2r69yorbdesguga10i.gif";
 Glide.with( context ) 
      .load( gifUrl ) 
      .into( imageViewGif );
asGif(): 检查Gif ,加载对象为非.gif的时候会当成加载错误处理asBitmap():把Gif当成常规静态图片来显示(只显示第一帧)
显示本地视频
注意,只能显示本地视频
String filePath = "/storage/emulated/0/Pictures/example_video.mp4"; 
Glide.with(context) 
     .load(Uri.fromFile(new File( filePath))) 
     .into(imageViewGifAsBitmap);
缓存
- 内存缓存: 
.skipMemoryCache(true)默认为false,说明Glide默认使用内存缓存,使用此方法会令Glide使用磁盘缓存而非内存缓存。对于相同URL的请求,如果没有调用此方法,那么Glide会从缓存中获取这个资源。例如:请求登录用户头像,URL一般来说是不会改变的,所以确保调用了此方法(设为true),否则如果用户更新了头像就无法显示出最新的头像图片资源 - 磁盘缓存: 
.diskCacheStrategy(enum e),可设值为DiskCacheStrategy.NONE表示禁用磁盘缓存 其他值:DiskCacheStrategy.NONE什么都不缓存,就像刚讨论的那样DiskCacheStrategy.SOURCE仅仅只缓存原来的全分辨率的图像。在我们上面的例子中,将会只有一个 1000x1000 像素的图片DiskCacheStrategy.RESULT仅仅缓存最终的图像,即,降低分辨率后的(或者是转换后的)DiskCacheStrategy.ALL缓存所有版本的图像(默认行为)- 禁用以上两者
 
    Glide.with(context) 
         .load(eatFoodyImages[0])
         .diskCacheStrategy(DiskCacheStrategy.NONE)    
         .skipMemoryCache(true)
         .into(imageViewInternet);
加载优先级
.priority()递增
Priority.LOWPriority.NORMALPriority.HIGHPriority.IMMEDIATE
略缩图
- 一种预加载方案,利用要加载图像背景的主色彩作为图像:参考这个方案
 .thumbnail(float scale):参数为原始图像的百分比,例如0.1f的 100x100像素的原始图,那么略缩图就是 10x10像素。这样做虽然方便,但是请求加载的是全像素的图像,如果图像越大就越耗时,在显示速度上得不到保证。- 略缩图和请求的全像素图片相互相互独立,为了解决上面大图像耗时问题
 
private void loadImageThumbnailRequest() {  
    // setup Glide request without the into() method 
    DrawableRequestBuilder<String> thumbnailRequest = Glide.with( context ).load(eatFoodyImages[2] );
    // pass the request as a a parameter to the thumbnail request 
    Glide.with(context) 
        .load(UsageExampleGifAndVideos.gifUrl)
        .thumbnail(thumbnailRequest) 
        .into(imageView3);
}
回调:Targets- SimpleTarget:
private SimpleTarget target = new SimpleTarget<Bitmap>() { 
    @Override 
    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
            // do something with the bitmap 
            // for demonstration purposes, let's just set it to an ImageView 
            imageView1.setImageBitmap( bitmap );
    }
};
private void loadImageSimpleTarget() { 
    Glide.with( context ) // could be an issue!
        .load( eatFoodyImages[0] ) 
        .asBitmap() 
        .into( target );
}
注意事项
- 调用
.asBitmap()是为了匹配SimpleTarget<Bitmap>中的参数对象,.into()方法可以传入ImageView或者Target对象。以上代码是一旦Glide已加载并处理完图像,它将被调用。 .into()中可以使用匿名内部类来新建Target对象,但是可能会造成,在Glide完成图片请求之前,垃圾回收机制会回收掉这个匿名内部类对象,造成回调无效的情况,所以不建议如此使用.with(context)问题,如果context是当前的Activity,当Activity停止的时候,Glide的请求就会自动停止。如果想避免这种情况,context应该用application的context, 这样处理会造成要等到应用完全停止时,Glide才会终止这些图片请求。
- 为Target指定大小
 
private SimpleTarget target2 = new SimpleTarget<Bitmap>( 250, 250 ) {  
    @Override 
    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
            imageView2.setImageBitmap(bitmap);
    }
};
private void loadImageSimpleTargetApplicationContext() {
    Glide.with(context.getApplicationContext()) // safer!       
        .load(eatFoodyImages[1]) 
        .asBitmap() 
        .into(target2);
}
- ViewTarget: 自定义View使用Glide
 
public class FutureStudioView extends FrameLayout {
        ImageView iv; 
        TextView tv;
        public void initialize(Context context) { 
                inflate( context, R.layout.custom_view_futurestudio, this ); 
                iv = (ImageView) findViewById( R.id.custom_view_image );
                tv = (TextView) findViewById( R.id.custom_view_text ); 
        } 
        public FutureStudioView(Context context, AttributeSet attrs) { 
                super( context, attrs );
                initialize( context ); 
        } 
        public FutureStudioView(Context context, AttributeSet attrs, int defStyleAttr) { 
                super( context, attrs, defStyleAttr ); 
                initialize( context ); 
        } 
        public void setImage(Drawable drawable) { 
                iv = (ImageView) findViewById( R.id.custom_view_image ); 
                iv.setImageDrawable( drawable ); 
        }
}
private void loadImageViewTarget() {  
        FutureStudioView customView = (FutureStudioView) findViewById( R.id.custom_view ); 
        viewTarget = new ViewTarget<FutureStudioView, GlideDrawable>( customView ) { 
                @Override 
                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) { 
                        this.view.setImage( resource.getCurrent() ); 
                } 
        }; 
        Glide.with( context.getApplicationContext() ) // safer! 
             .load( eatFoodyImages[2] )
             .into( viewTarget );
}
可以使用Glide显示图片到Notifications和App Widgets
异常处理
Transformations
- 转换,可以实现颜色、尺寸、范围和像素为止等等。比如
fitCenter()、centerCrop()也属于转换的一种。或者可以进行模糊化blur、圆形头像等转换。 - 一般常用的抽象类
BitmapTransformation(仅限于bimap的转换)。 - 多种转换,
.transform()、.bitmapTransform()可接受多个转换对象作为参数。 
一个转换集合的库: glide-transformations
使用了
Transformations后就不能再使用centerCrop()和fitCenter()了,不然转换会失效,被后者的效果所覆盖
animate() 过渡动画
- 过渡动画仅仅用于不从缓存中加载的情况。如果图片被缓存过,它的显示很快就没有必要用
animate() - 可以使用在XML创建的动画资源- 可以创建实现
ViewPropertyAnimation.Animator接口的类 
Glide Modules
- 定制Glide,比如Glide默认使用较低质量的图片解码方式
RGB565,如果想改变使用高质量的ARGB8888,可以自定义GlideModules: 
自定义GlideModules,简单来说,需要1)实现GlideModule接口,2)在
Manifest.xml的<application>标签内声明
public class SimpleGlideModule implements GlideModule {    
        @Override 
        public void applyOptions(Context context, GlideBuilder builder) { 
                builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); 
          } 
        @Override 
        public void registerComponents(Context context, Glide glide) { 
                // nothing to do here 
        }
}
网络请求相关
- Glide内部使用了标准的
HTTPURLConnection去下载图片 - 如果服务端使用的是
HTTPS,而且是自签名的(self-signed),Glide不会下载或显示图片 
旋转图片
public class RotateTransformation extends BitmapTransformation { 
        private float rotateRotationAngle = 0f; 
        
        public RotateTransformation(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); 
                return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true); 
        } 
        @Override 
        public String getId() { 
                return "rotate" + rotateRotationAngle;
        }
}
//Usage
private void loadImageRotated() {  
        Glide .with( context ) 
               .load( eatFoodyImages[0] ) 
               .transform( new RotateTransformation( context, 90f ))               
               .into( imageView3 );
}
坑
- 使用第三方的
CircleImage要调用dontAnimate(),不然图片无法正常加载