谷歌在2014开发者论坛上,为我们介绍了一个名叫Glide的图片加载库,这个库被广泛的运用在Google的开源项目中。 Glide是Android中的一个快速和高效的开源媒体管理,图片加载框架。它封装了媒体解码,内存和磁盘缓存,将资源池变成一个简单一用的界面。支持获取解码,显示视频,图片,和Gif动画。Glide提供了一个灵活的API,允许开发人员自定义使用任何网络框架。默认情况下,使用一个基于HttpUrlConnection 的网络访问,但是同样包含了工具库插件支持其它的网络访问库,比如Volly或者OkHttp库。Glide的主要重点是使滚动任何形式的图片列表尽可能的平滑而且快速,但是Glide在任何你需要获取,调整,显示网络图片时同样的高效。
github地址:https://github.com/bumptech/glide
1.在build.gradle中添加依赖: compile ‘com.github.bumptech.glide:glide:3.7.0’ 需要support-v4库的支持,如果你的项目没有support-v4库(现在项目一般默认添加),还需要添加support-v4依赖: compile ‘com.android.support:support-v4:19.1.0’
2.配置混淆规则:
-keep public class * implements com.bumptech.glide.module.GlideModule -keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser** { **[]VALUES; public *; } -keePResourcexmlelements manifest/application/meta-data@value=GlideModule
3.集成网络访问框架OkHttp(可选)
Glide默认使用HttpUrlConnection进行网络请求,为了让APP保持一致的网络请求形式,可以指定Glide的网络请求形式,我们可以选Volley或者OkHttp,这里我们选OkHttp,还需要添加一个集成库: compile ‘com.github.bumptech.glide:okhttp3-integration:1.4.0@aar’ //compile ‘com.squareup.okhttp3:okhttp:3.2.0’
注意: 1. Gradle会自动将OkHttpGlideModule合并到应用的manifest文件中。 2. 如果你没有对所有的GlideModule配置混淆规则(即没有使用-keep public class * implements com.bumptech.glide.module.GlideModule),则需要把OkHttp的GlideModule进行防混淆配置: -keep class com.bumptech.glide.integration.okhttp3.OkHttpGlideModule
简单使用: ImageView imageView = (ImageView) findViewById(R.id.imageview); Glide.with(this) .load(R.drawable.launchimage) .into(imageView);
Glide.with()使用 1.with(Context context):使用Application作为上下文,Glide请求将不受Activity/Fragment生命周期控制。 2.with(Activity activity):使用Activity作为上下文,Glide请求受到Activity生命周期控制。 3.with(FragmentActivity activity):使用FragmentActivity 作为上下文,Glide的请求会受到FragmentActivity 生命周期控制。 4.with(android.app.Fragment fragment):Glide请求受到Fragment 生命周期控制。 5.with(Fragment fragment):同上;
以上会返回关联上下文的RequestManager示例。
RequestManager.load()使用 Glide基本上可以load任何可以拿到的媒体资源,如:
load SD卡资源:load("file://"+ Environment.getExternalStorageDirectory().getPath()+"/test.jpg") load assets资源:load("file:///android_asset/f003.gif") load raw资源:load("Android.resource://"+getPackageName()+"/raw_1")或load("android.resource://"+getPackageName()+"/"+R.raw.raw_1) load drawable资源:load(R.drawable.launchimage)load ContentProvider资源:load("content://media/external/images/media/139469")load http资源:load("http://***")load https资源:load("https://****") 当然,load不限于String类型,还可以:load(Uri uri),load(File file),load(Integer resourceId),load(URL url),@Deprecatedload(byte[] model),load(T model),loadFromMediaStore(Uri uri)。一个工具方法:简单的将资源 id 转换成 Uri。
public static final String ANDROID_RESOURCE = "android.resource://";public static final String FOREWARD_SLASH = "/";private static Uri resourceIdToUri(Context context, int resourceId) { return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FOREWARD_SLASH + resourceId);}新闻热点
疑难解答