1 基本使用
Glide.with(this).load(INTERNET_PIC_URL_1).into(imageView);
2 常用设置
Glide.with(context)
// 使用.asXX设置图片类型
.load(url) // 可以设置url地址、本地地址、资源等
.override(360, 270) // 图片尺寸
.skipMemoryCache(true) // 是否禁止缓存。默认为false,使用缓存。
// 设置磁盘缓存策略
// DiskCacheStrategy: .ALL .NONE .SOURCE .RESULT
.diskCacheStrategy(DiskCacheStrategy.ALL)
// 占位图 (未加载前的等待)
.placeholder(R.drawable.ic_baseline_photo_24)
// 错误提示图
.error(R.drawable.ic_baseline_error_24)
// 不使用动画效果
.dontAnimate()
.into(imageView);
// 清除内存缓存
Glide.get(this).clearMemory();
// 清除磁盘缓存
Glide.get(this).clearDiskCache();
3.1 使用 TransitionOptions
// 添加渐入效果
// 1 创建渐入效果 Factory
DrawableCrossFadeFactory crossFadeFactory
= new DrawableCrossFadeFactory
.Builder(500)
.setCrossFadeEnabled(true)
.build();
// 2 生成 DrawableTransitionOptions
DrawableTransitionOptions options = DrawableTransitionOptions.with(crossFadeFactory);
Glide
.with(context)
.load(url)
// 3 设置 DrawableTransitionOptions
.transition(options)
.into(imageView);
3.2 定制 Transformation
Glide.with(this).load(INTERNET_PIC_URL_1).transform(new CustTransformation(10f));
public class CustTransformation extends BitmapTransformation {
private static final String ID
= "com.lingchen.practiceproject.glide.CustTransformation";
private float radius;
public CustTransformation(float radius) {
this.radius = radius;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform,
int outWidth, int outHeight) {
return cornersCrop(pool, toTransform);
}
// 圆角
private Bitmap cornersCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(),
source.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(),
source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source,
BitmapShader.TileMode.CLAMP,
BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update((ID + radius).getBytes(CHARSET));
}
@Override
public boolean equals(Object o) {
return o instanceof CustTransformation;
}
}
4 使用 RequestOptions
RequestOptions requestOptions = new RequestOptions();
requestOptions.circleCrop();
requestOptions.optionalTransform(new CircleCrop());
requestOptions.optionalTransform(new RoundedCorners(300));
requestOptions.optionalTransform(new CustTransformation(200));
Glide.with(this)
.load(INTERNET_PIC_URL_1)
.apply(requestOptions)
.into(imageView3);