Glide图片缓存
1实现
1.1Glide缓存配置
没有声明不会使用缓存
需要在AndroidManifest.xml中配置声明
<meta-data android:name="com.yaphetzhao.glidecatchsimple.glide.GlideConfiguration" android:value="GlideModule" />
代码:
public class GlideConfiguration implements GlideModule {
// 需要在AndroidManifest.xml中声明
/*<meta-data
android:name="com.yaphetzhao.glidecatchsimple.glide.GlideConfiguration"
android:value="GlideModule" />*/
/**
* 自定义缓存目录
*
* @param context 上下文
* @param builder Glide建设者
*/
@Override
public void applyOptions(Context context, GlideBuilder builder) {
builder.setDiskCache(new InternalCacheDiskCacheFactory(context, GlideCatchConfig.GLIDE_CARCH_DIR, GlideCatchConfig.GLIDE_CATCH_SIZE));
}
@Override
public void registerComponents(Context context, Glide glide) {
}
}
1.2Glide缓存配置
public class GlideCatchConfig {
public static final int GLIDE_CATCH_SIZE = 150 * 1000 * 1000;//最大容量150M
public static final String GLIDE_CARCH_DIR = "glideimg_catch";//图片缓存子目录
}
1.3Glide缓存工具类
@SuppressWarnings("ResultOfMethodCallIgnored")
public class GlideCacheUtils {
private static GlideCacheUtils instance;
public static GlideCacheUtils getInstance() {
if (null == instance) {
instance = new GlideCacheUtils();
}
return instance;
}
/**
* 获取Glide磁盘缓存大小
*
* @param mContext 上下文
* @return 缓存大小
*/
public String getCacheSize(Context mContext) {
try {
return getFormatSize(getFolderSize(new File(mContext.getCacheDir() + "/" + GlideCatchConfig.GLIDE_CARCH_DIR)));
} catch (Exception e) {
e.printStackTrace();
return "获取失败";
}
}
/**
* 清除Glide磁盘缓存,自己获取缓存文件夹并删除方法
*
* @param mContext 上下文
* @return 是否清除
*/
public boolean cleanCatchDisk(Context mContext) {
return deleteFolderFile(mContext.getCacheDir() + "/" + GlideCatchConfig.GLIDE_CARCH_DIR, true);
}
/**
* 清除图片磁盘缓存,调用Glide自带方法
*
* @param mContext 上下文
* @return 是否清除
*/
public boolean clearCacheDiskSelf(final Context mContext) {
try {
if (Looper.myLooper() == Looper.getMainLooper()) {
new Thread(() -> Glide.get(mContext).clearDiskCache()).start();
} else {
Glide.get(mContext).clearDiskCache();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 清除Glide内存缓存
*
* @param mContext 上下文
* @return 是否清除
*/
public boolean clearCacheMemory(Context mContext) {
try {
if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
Glide.get(mContext).clearMemory();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取指定文件夹内所有文件大小的和
*
* @param file 文件
* @return 大小
*/
private long getFolderSize(File file) {
long size = 0;
try {
File[] fileList = file.listFiles();
for (File aFileList : fileList) {
if (aFileList.isDirectory()) {
size = size + getFolderSize(aFileList);
} else {
size = size + aFileList.length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
/**
* 格式化单位
*
* @param size 大小
* @return 大小
*/
private static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
/**
* 按目录删除文件夹文件方法
*
* @param filePath 文件路径
* @param deleteThisPath 删除路径
* @return 是否删除
*/
private boolean deleteFolderFile(String filePath, boolean deleteThisPath) {
try {
File file = new File(filePath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File file1 : files) {
deleteFolderFile(file1.getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {
file.delete();
} else {
if (file.listFiles().length == 0) {
file.delete();
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
2Glide使用
2.1常规使用
Glide.with(this)
.load(ivUrl)//链接
.skipMemoryCache(true)//跳过内存缓存
.diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
.signature( new StringSignature(strSign))//增加签名strSign:标志String
.into(iv);//所要加载的控件
2.1.1 使用磁盘缓存
将GlideConfiguration 添加到清单文件中
Glide.with(this)
.load(ivUrl)
.placeholder(R.drawable.img_error)//占位
.error(R.drawable.img_error)//错误图
.signature(new StringSignature(strSign))//增加签名strSign:标志后台配置最好
.into(iv);
2.2圆角
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 4);
}
public GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
private static Bitmap roundCrop(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 String getId() {
return getClass().getName() + Math.round(radius);
}
}
使用:
Glide.with(this)
.load(ivUrl)
.placeholder(R.drawable.img_error)
.error(R.drawable.img_error)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.transform(new GlideRoundTransformation(this, 10))
.into(iv);
2.2.1错误情况:
2.2.1.1加载Gif圆角图多次后出现黑边
此错误情况参考这篇使用这里只写解决方案。
final DrawableRequestBuilder<String> builder = Glide.with(this).load(iv_url).error(R.drawable.img_error).placeholder(R.drawable.img_error).crossFade().diskCacheStrategy(DiskCacheStrategy.SOURCE);
//监听是否加载完成
builder.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String s, Target<GlideDrawable> target, boolean b) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model,
Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
int radiusDp = 10;//圆角大小
builder.bitmapTransform(new GlideRoundTransformation(activity, radiusDp));
return false;
}
}).into(iv);