Glide V4的封装使用

来源:互联网 发布:一级域名申请 编辑:程序博客网 时间:2024/05/17 02:57
Glide配置

添加对 Glide 的注解和注解解析器的依赖:

implementation 'com.github.bumptech.glide:glide:4.3.1'annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

混淆设置,把以下代码添加到你的 proguard.cfg 文件中:

-keep public class * implements com.bumptech.glide.module.GlideModule-keep public class * extends com.bumptech.glide.AppGlideModule-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {**[] $VALUES;public *;}

在 Application 模块中创建AppGlideModule

import com.bumptech.glide.annotation.GlideModule;import com.bumptech.glide.module.AppGlideModule;/** * Glide配置类 * Created by HeDongDong on 2017/11/21. */@GlideModulepublic final class MyAppGlideModule extends AppGlideModule {    /**     * 禁用清单解析     * 这样可以改善 Glide 的初始启动时间,并避免尝试解析元数据时的一些潜在问题。     *     * @return     */    @Override    public boolean isManifestParsingEnabled() {    return false;    }}

你可以在子类中实现AppGlideModule 的任意方法来封装你的需求,比如:缓存大小.它只需要继承 AppGlideModule 并且必须添加 @GlideModule 注解。

基本用法

封装一个工具类

/*** 图片加载工具类*/public class ImageLoadUtil {/** * 正常加载图片 * * @param context * @param iv       ImageView * @param url      图片地址 * @param emptyImg 默认占位图 */public static void displayImage(Context context, ImageView iv, String url, int emptyImg) {    GlideApp.with(context)            .load(url)            .placeholder(emptyImg)            .into(iv);    }}

Glide允许用户指定三种不同类型的占位符,分别在三种不同场景使用:

placeholder(占位符)error (错误符)fallback(后备服务符)
圆角实现

RoundedCorners

 GlideApp.with(context)         .load(url)         .transform(new RoundedCorners(20)) //此处为圆角px值         .into(iv);
圆形实现

CircleCrop

    GlideApp.with(context)            .load(TextUtils.isEmpty(url)?url:new MyGlideUrl(url))            .transform(new CircleCrop(context))            .into(iv);
自定义缓存地址设置

继承GlideUrl 重写getCacheKey()

/** * 自定义缓存key规则 * Created by HeDongDong on 2017/11/22. */public class MyGlideUrl extends GlideUrl {    private String mUrl;    /**     * 注: url不能为空     *     *     url不能为空     *     *     url不能为空     *     *  重要的事要说三遍     */    public MyGlideUrl(String url) {        super(url);        mUrl = url;    }    @Override    public String getCacheKey() {        //TODO 此处设置缓存Key        if (mUrl.contains("?")) {            mUrl = mUrl.substring(0, mUrl.indexOf("?"));        }        return mUrl;    }}

然后替换load(url)

GlideApp.with(context)            .load(new MyGlideUrl(url))            .placeholder(emptyImg)            .into(iv);

官方中文资料:https://muyangmin.github.io/glide-docs-cn/

参考资料:http://blog.csdn.net/guolin_blog/article/details/54895665#t4

原创粉丝点击