配置类:
package com.itant.zhuling.tool.image.glide;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.GlideModule;
/**
* 混淆的话,要在proguard-rules.pro添加-keepnames class * 完整包名.CustomCachingGlideModule
*
*/
public class CustomCachingGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
// 设置磁盘缓存为100M,缓存在内部缓存目录
int cacheSize100MegaBytes = 104857600;
builder.setDiskCache(
new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)
);
//builder.setDiskCache(
//new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
// 20%大的内存缓存作为 Glide 的默认值
MemorySizeCalculator calculator = new MemorySizeCalculator(context);
int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);
builder.setMemoryCache( new LruResourceCache(customMemoryCacheSize));
builder.setBitmapPool( new LruBitmapPool(customBitmapPoolSize));
}
@Override
public void registerComponents(Context context, Glide glide) {
// nothing to do here
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
清单文件application节点添加(name为配置文件完整包名,value的”GlideModule”为固定值。):
<meta-data android:name="com.itant.zhuling.tool.image.glide.CustomCachingGlideModule"
android:value="GlideModule"/>
- 1
- 2
使用:
Glide.with(MeizhiActivity.this)
.load(item.getUrl())
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.ALL)// 缓存所有尺寸的图片
.thumbnail( 0.1f )//先加载原图大小的十分之一
.into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
int imageWidth = resource.getWidth();
int imageHeight = resource.getHeight();
// 减去间距
int height = (screenWidth - dividerWidth * 3) / 2 * imageHeight / imageWidth;
ViewGroup.LayoutParams para = iv_meizhi.getLayoutParams();
para.height = height;
para.width = (screenWidth - dividerWidth * 3) / 2;
iv_meizhi.setImageBitmap(resource);
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
你还可以使用
.placeHloder(...)
.error(...)
- 1
- 2
设置默认图片,由于我这里是在列表中使用,viewholder中已经处理并设置默认图片,就不使用这两个方法了。