1、环境配置
首先在Android studio中导入依赖
compile 'com.github.bumptech.glide:glide:3.7.0'需要support-v4库的支持,如果你的项目没有support-v4库(项目默认已经添加了),还需要添加support-v4依赖:
compile 'com.android.support:support-v4:23.3.0'然后配置混淆:
//不混淆所有的GlideModule-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** { **[] $VALUES; public *;}
记得在清单文件中添加相应的权限:
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />2、基本使用
Glide.with(this) .load(url)//加载图片 .placeholder(R.mipmap.ic_launcher)//正在加载时的图片 .error(R.mipmap.ic_launcher)//加载错误时的图片 .into(glide_image); .transform(new CircleTransform(this))
//通过Glide的TransForMation 自定义圆形图片的bitmapGlide.with()使用
- with(Context context):使用Application上下文,Glide请求将不受Activity/Fragment生命周期控制。
- with(Activity activity):使用Activity作为上下文,Glide的请求会受到Activity生命周期控制。
- with(FragmentActivity activity):Glide的请求会受到FragmentActivity生命周期控制。
- with(android.app.Fragment fragment):Glide的请求会受到Fragment 生命周期控制。
-
with(android.support.v4.app.Fragment fragment):Glide的请求会受到Fragment生命周期控制。
Glide基本本可以load任何可以拿到的媒体资源,如:
- load(String string)
-
load SD卡资源:load("file://"+ Environment.getExternalStorageDirectory().getPath()+"/test.jpg")load assets资源:load("file:///android_asset/f003.gif")load raw资源:load("Android.resource://com.frank.glide/raw/raw_1")或 load("android.resource://com.frank.glide/raw/"+R.raw.raw_1)load drawable资源:load("android.resource://com.frank.glide/drawable/news")或 load("android.resource://com.frank.glide/drawable/"+R.drawable.news)load ContentProvider资源:load("content://media/external/images/media/139469")load http资源:load("http://img.my.csdn.net/uploads/201508/05/1438760757_3588.jpg")load https资源:load("https://img.alicdn.com/tps/TB1uyhoMpXXXXcLXVXXXXXXXXXX-476-538.jpg_240x5000q50.jpg_.webp")
当然,load不限于String类型,还可以:
-
load(File file):@param file:The File containing the image。
-
load(Integer resourceId):@param resourceId :the id of the resource containing the image。可以用R.drawable或R.mipmap
- load(Uri uri):@param uri:The Uri representing the image. Must be of a type handled by UriLoader
-
load(byte[] model):@param model:the data to load.
-
loadFromMediaStore(Uri uri):@param uri:The uri representing the media.
-
load(T model):@param model:The model the load.
load(URL url):deprecated
3、其他使用
禁止内存缓存:
Glide.skipMemoryCache(true)
清除内存缓存:
// 必须在UI线程中调用 Glide.get(context).clearMemory();
禁止磁盘缓存:
Glide.diskCacheStrategy(DiskCacheStrategy.NONE)
清除磁盘缓存:
// 必须在后台线程中调用,建议同时clearMemory() Glide.get(applicationContext).clearDiskCache();
获取缓存大小:
new GetDiskCacheSizeTask(textView).execute(new File(getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long> {private final TextView resultView; public GetDiskCacheSizeTask(TextView resultView) { this.resultView = resultView;} @Overrideprotected void onPreExecute() { resultView.setText("Calculating...");} @Overrideprotected void onProgressUpdate(Long... values) { /* onPostExecute(values[values.length - 1]); */ } @Overrideprotected Long doInBackground(File... dirs) { try { long totalSize = 0; for (File dir : dirs) { publishProgress(totalSize); totalSize += calculateSize(dir); } return totalSize; } catch (RuntimeException ex) { final String message = String.format("Cannot get size of %s: %s", Arrays.toString(dirs), ex); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { resultView.setText("error"); Toast.makeText(resultView.getContext(), message, Toast.LENGTH_LONG).show(); } }); } return 0L;} @Overrideprotected void onPostExecute(Long size) { String sizeText = android.text.format.Formatter.formatFileSize(resultView.getContext(), size); resultView.setText(sizeText);} private static long calculateSize(File dir) { if (dir == null) return 0; if (!dir.isDirectory()) return dir.length(); long result = 0; File[] children = dir.listFiles(); if (children != null) for (File child : children) result += calculateSize(child); return result;}}
指定资源的优先加载顺序:
//优先加载 Glide .with(context) .load(heroImageUrl) .priority(Priority.HIGH) .into(imageViewHero); //后加载 Glide .with(context) .load(itemImageUrl) .priority(Priority.LOW) .into(imageViewItem);
先显示缩略图,再显示原图:
//用原图的1/10作为缩略图 Glide .with(this) .load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png") .thumbnail(0.1f) .into(iv_0); //用其它图片作为缩略图 DrawableRequestBuilder<Integer> thumbnailRequest = Glide .with(this) .load(R.drawable.news); Glide.with(this) .load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png") .thumbnail(thumbnailRequest) .into(iv_0); compile 'jp.wasabeef:glide-transformations:2.0.0'
之后我们就可以使用GenericRequestBuilder或其子类的
transform()或bitmapTransform()方法设置图片转换了://圆形裁剪 Glide.with(this) .load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png") .bitmapTransform(new CropCircleTransformation(this)) .into(iv_0); //圆角处理 Glide.with(this) .load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png") .bitmapTransform(new RoundedCornersTransformation(this,30,0, RoundedCornersTransformation.CornerType.ALL)) .into(iv_0); //灰度处理 Glide.with(this) .load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png") .bitmapTransform(new GrayscaleTransformation(this)) .into(iv_0); //其它变换...
4、基于Glide的优秀库
一个基于Glide的transformation库,拥有裁剪,着色,模糊,滤镜等多种转换效果。
一个可以在Glide加载时很方便使用Palette的库。
详谈高图片加载框架Glide -应用篇: http://www.jianshu.com/p/cea08d72ad4c