Glide load(xxx)源码分析

Glide.with(this).load(url).into(imageView);

Glide调用with()方法初始化成功后,会返回RequestManager的实例。

1、RequestManager类中有多个load()的重载方法


  public RequestBuilder load(@Nullable Bitmap bitmap) {
    return asDrawable().load(bitmap);
  }

  public RequestBuilder load(@Nullable Drawable drawable) {
    return asDrawable().load(drawable);
  }

  public RequestBuilder load(@Nullable String string) {
    return asDrawable().load(string);
  }


  public RequestBuilder load(@Nullable Uri uri) {
    return asDrawable().load(uri);
  }

  public RequestBuilder load(@Nullable File file) {
    return asDrawable().load(file);
  }

  public RequestBuilder load(@RawRes @DrawableRes @Nullable Integer resourceId) {
    return asDrawable().load(resourceId);
  }

  public RequestBuilder load(@Nullable URL url) {
    return asDrawable().load(url);
  }


  public RequestBuilder load(@Nullable byte[] model) {
    return asDrawable().load(model);
  }

  public RequestBuilder load(@Nullable Object model) {
    return asDrawable().load(model);
  }

2、asDrawable()

  @NonNull
  @CheckResult
  public RequestBuilder asDrawable() {
    return as(Drawable.class);
  }

 -->新建一个RequestBuilder
  @NonNull
  @CheckResult
  public  RequestBuilder as(
      @NonNull Class resourceClass) {
    return new RequestBuilder<>(glide, this, resourceClass, context);
  }


-->RequestBuilder的创建
public class RequestBuilder extends BaseRequestOptions>
    implements Cloneable,
    ModelTypes> {

  @Nullable private Object model;
  private final Context context;
  private final Glide glide;
  private final RequestManager requestManager;
  private final Class transcodeClass;
  private TransitionOptions transitionOptions;//过渡动画配置
  private final GlideContext glideContext;

  protected RequestBuilder(
      @NonNull Glide glide,
      RequestManager requestManager,
      Class transcodeClass,
      Context context) {
    this.glide = glide;
    this.requestManager = requestManager;
    this.transcodeClass = transcodeClass; //Drawable.class
    this.context = context;
    this.transitionOptions = requestManager.getDefaultTransitionOptions(transcodeClass);设置默认的过渡动画
    this.glideContext = glide.getGlideContext();

    //设置RequestListener集合
    //用来给调用者监听图片的加载成功和失败
    initRequestListeners(requestManager.getDefaultRequestListeners());

    //设置默认的请求配置,DefaultRequestOptions()只是一个new RequestOptions()
    apply(requestManager.getDefaultRequestOptions());
  }

}

RequestBuilder 用来构建请求,例如设置 RequestOption、缩略图、过渡动画、加载失败占位图等等。

3、asDrawable().load(xxx)

public class RequestBuilder {

  @NonNull
  private RequestBuilder loadGeneric(@Nullable Object model) {
    this.model = model;
    isModelSet = true;
    return this;
  }

}

RequestManager的多个load重载方法,最后都一定会调用到RequestBuilder的loadGeneric,loadGeneric方法是用来设置图片资源的来源类型为String;这里有个Model的概念,指的是图片数据来源,可以是本地的图片链接,可以是url,可以drawable的资源id。

总结:load(xxx)方法实际上就是用来构建RequestBuilder实例,并且设置图片资源的来源类型。

你可能感兴趣的:(Glide load(xxx)源码分析)