1、Android Studio依赖添加
dependencies { compile 'com.github.bumptech.glide:glide:3.5.2' compile 'com.android.support:support-v4:22.0.0' } Glide需要依赖 Support Library v4。
2、使用
Glide.with(context)//此处不仅可以传Context,还可以传Activity和Fragment,推荐使用后两种,这样可以保持图片加载与其生命周期一致 .load(url)//图片地址,此处可放gif .placeholder(R.drawable.loading)//占位符,加载时显示的图片,可放gif .asGif()//只能加载gif文件 .error(R.drawable.failed) //加载失败图片 .crossFade(1000) //添加图片淡入效果, 可设置时长,默认“300ms” .into(view); 3、Bitmap设置默认Bitmap格式是RGB_565,占用内存较小,也可自定义修改。
public class GlideConfiguration implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { // Apply options to the builder here. builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); } @Override public void registerComponents(Context context, Glide glide) { // register ModelLoaders here. } }同时在AndroidManifest.xml中将GlideModule定义为meta-data <meta-data android:name="com.inthecheesefactory.lab.glidepicasso.GlideConfiguration" android:value="GlideModule"/> 4、缓存Glide默认开启磁盘缓存和内存缓存,当然也可以对单张图片进行设置特定的缓存策略。 设置图片不加入到内存缓存
Glide.with(context) .load(url) .skipMemoryCache(true) .into(imageViewInternet); 设置图片不加入到磁盘缓存 Glide.with(context) .load(url) .diskCacheStrategy(DiskCacheStrategy.NONE) .into(imageViewInternet); Glide支持多种磁盘缓存策略: DiskCacheStrategy.NONE :不缓存图片 DiskCacheStrategy.SOURCE :缓存图片源文件 DiskCacheStrategy.RESULT:缓存修改过的图片 ,默认 DiskCacheStrategy.ALL:缓存所有的图片Glide会自动获取ImageView的大小,根据view的尺寸加载不同大小的图片存于内存。不过这也导致了Glide每加载一次不同大小的图片都会进行缓存,也就意味着需要进行多次下载。
我们可以通过设置
diskCacheStrategy(DiskCacheStrategy.ALL)让Glide既缓存全尺寸又缓存其他尺寸,下次在任何ImageView中加载图片的时候,全尺寸的图片将从缓存中取出,重新调整大小,然后缓存。
缓存清除
Glide自带清除缓存的功能,分别对应
Glide.get(context).clearDiskCache();(清除磁盘缓存)
Glide.get(context).clearMemory();(清除内存缓存)
两个方法.其中clearDiskCache()方法必须运行在子线程,clearMemory()方法必须运行在主线程,这是这两个方法所强制要求的,详见源码.
import android.content.Context; import android.os.Looper; import android.text.TextUtils; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory; import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory; import java.io.File; import java.math.BigDecimal; /**Glide缓存工具类 * Created by Trojx on 2016/10/10 0010. */ public class GlideCacheUtil { private static GlideCacheUtil inst; public static GlideCacheUtil getInstance() { if (inst == null) { inst = new GlideCacheUtil(); } return inst; } /** * 清除图片磁盘缓存 */ public void clearImageDiskCache(final Context context) { try { if (Looper.myLooper() == Looper.getMainLooper()) { new Thread(new Runnable() { @Override public void run() { Glide.get(context).clearDiskCache(); // BusUtil.getBus().post(new GlideCacheClearSuccessEvent()); } }).start(); } else { Glide.get(context).clearDiskCache(); } } catch (Exception e) { e.printStackTrace(); } } /** * 清除图片内存缓存 */ public void clearImageMemoryCache(Context context) { try { if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行 Glide.get(context).clearMemory(); } } catch (Exception e) { e.printStackTrace(); } } /** * 清除图片所有缓存 */ public void clearImageAllCache(Context context) { clearImageDiskCache(context); clearImageMemoryCache(context); String ImageExternalCatchDir=context.getExternalCacheDir()+ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR; deleteFolderFile(ImageExternalCatchDir, true); } /** * 获取Glide造成的缓存大小 * * @return CacheSize */ public String getCacheSize(Context context) { try { return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/"+InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR))); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 获取指定文件夹内所有文件大小的和 * * @param file file * @return size * @throws Exception */ private long getFolderSize(File file) throws Exception { 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 filePath filePath * @param deleteThisPath deleteThisPath */ private void deleteFolderFile(String filePath, boolean deleteThisPath) { if (!TextUtils.isEmpty(filePath)) { 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(); } } } } catch (Exception e) { e.printStackTrace(); } } } /** * 格式化单位 * * @param size size * @return size */ 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"; } } 4、显示圆图 public class GlideCircleTransform extends BitmapTransformation { public GlideCircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static 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; // TODO this could be acquired from the pool too Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); return result; } @Override public String getId() { return getClass().getName(); } } Glide.with(mContext) .load(imageUrl) .transform(new GlideCircleTransform(mContext)) .into(holder.imageView);另:在简书上有一系列关于Glide的详细文章,大家可以去学习一下
http://www.jianshu.com/p/7610bdbbad17