好像是一年前快两年了,笔者解析过glide的源码,也是因为觉得自己熟悉一些,也就没太关注过项目里glide的具体使用对当前业务的影响;主要是自负,还有就是真没有碰到过这样的数据加载情况。暴露了经验还是不太足够
有兴趣的可以去瞅瞅,就是对源码的解释而已比较枯燥乏味。也是因为有了这个积累才能找到比较合适的参数比解决当前的问题:
传送门:Glide源码解析
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP
优化之前的用法如下:

 					Glide.with(context)
 						.load(imgUrl)
                        .into(holder.imageview);

因为不是笔者自己写的这段加载逻辑,所以笔者也没改动,呃!搞开发的都知道,程序能运行就别动;再说笔者就是一个小虾米,又在一个还算那啥的体系里。多一事不如少一事,搞开发也要讲讲人情世故蛤!不过一年前负责这块的开发跳槽了,据说工资涨了一大截;也算是happy跳槽。

优化之后的图片加载渲染就顺畅很多了,再没有上下滑动过程中出现的那种一顿一顿的画面顿感了,解决了在滑动过程中因为网络图片过重导致的渲染卡顿问题

下面针对几个优化参数设置进行细化解析:

thumbnail(0~1.0f)

原文介绍如下:

/**
   * Loads a resource in an identical manner to this request except with the dimensions of the
   * target multiplied by the given size multiplier. If the thumbnail load completes before the full
   * size load, the thumbnail will be shown. If the thumbnail load completes after the full size
   * load, the thumbnail will not be shown.
   *
   * <p>Note - The thumbnail resource will be smaller than the size requested so the target (or
   * {@link ImageView}) must be able to scale the thumbnail appropriately. See
   * {@link android.widget.ImageView.ScaleType}.
   *
   * <p>Almost all options will be copied from the original load, including the {@link
   * com.bumptech.glide.load.model.ModelLoader}, {@link com.bumptech.glide.load.ResourceDecoder},
   * and {@link com.bumptech.glide.load.Transformation}s. However,
   * {@link com.bumptech.glide.request.RequestOptions#placeholder(int)} and
   * {@link com.bumptech.glide.request.RequestOptions#error(int)}, and
   * {@link #listener(RequestListener)} will only be used on the full size load and will not be
   * copied for the thumbnail load.
   *
   * <p>Recursive calls to thumbnail are supported.
   *
   * <p>Overrides any previous calls to this method, {@link #thumbnail(RequestBuilder[])},
   *  and {@link #thumbnail(RequestBuilder)}.
   *
   * @see #thumbnail(RequestBuilder)
   * @see #thumbnail(RequestBuilder[])
   *
   * @param sizeMultiplier The multiplier to apply to the {@link Target}'s dimensions when loading
   *                       the thumbnail.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  @SuppressWarnings("unchecked")
  public RequestBuilder<TranscodeType> thumbnail(float sizeMultiplier) {
    if (sizeMultiplier < 0f || sizeMultiplier > 1f) {
      throw new IllegalArgumentException("sizeMultiplier must be between 0 and 1");
    }
    this.thumbSizeMultiplier = sizeMultiplier;

    return this;
  }

GPT翻译如下:

/**

以与此请求相同的方式加载资源,但是目标的尺寸乘以给定的尺寸倍数。如果缩略图加载在完整尺寸加载之前完成,将显示缩略图。如果缩略图加载在完整尺寸加载之后完成,将不会显示缩略图。

<p>注意 - 缩略图资源将小于请求的尺寸,因此目标(或{@link ImageView})必须能够适当地缩放缩略图。请参阅{@link android.widget.ImageView.ScaleType}。
<p>几乎所有选项都将从原始加载复制,包括{@link com.bumptech.glide.load.model.ModelLoader}、{@link com.bumptech.glide.load.ResourceDecoder}和{@link com.bumptech.glide.load.Transformation}。但是,{@link com.bumptech.glide.request.RequestOptions#placeholder(int)}和{@link com.bumptech.glide.request.RequestOptions#error(int)},以及{@link #listener(RequestListener)} 仅在完整尺寸加载时使用,并且不会被复制到缩略图加载。
<p>支持对缩略图的递归调用。
<p>覆盖对此方法的先前调用,{@link #thumbnail(RequestBuilder[])}和{@link #thumbnail(RequestBuilder)}。
@see #thumbnail(RequestBuilder)

@see #thumbnail(RequestBuilder[])

@param sizeMultiplier 加载缩略图时要应用于{@link Target}尺寸的倍数。

@return 此请求构建器。 */ 

优化之前的,这个空白和缩略图没有关系蛤!
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP

优化之后的实际效果展示:
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP
也是由于图片太重了,当这个方法加上的时候,上下滑动立马就顺畅了很多,笔者实际使用的参数值是:
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP
0.0625f 这个参数值我自己都惊讶了!不要问这个参数怎么来的,问就是二分法
好,接着设置RequestOptions

RequestOptions

下面是优化后的使用

public static RequestOptions buildRequestOptions(Context context, int resId) {
        if (null != gridAdapterRequestOptions)
            return gridAdapterRequestOptions;
        gridAdapterRequestOptions = RequestOptions.noTransformation();
        return gridAdapterRequestOptions
                .sizeMultiplier(0.85f)
//                .skipMemoryCache(true) // 跳过内存缓存
//                .onlyRetrieveFromCache(true)

//                .diskCacheStrategy(DiskCacheStrategy.NONE) // 跳过磁盘缓存
                .override(63 * 2, 112 * 2)
                .dontAnimate()
//                .error(resId)
                .placeholder(resId)
                ;
    }

placeholder(resId)

这个大家都熟悉就不解释了,贴个原文水一下:

/**
   * Sets an Android resource id for a {@link Drawable} resource to
   * display while a resource is loading.
   *
   * @param resourceId The id of the resource to use as a placeholder
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions placeholder(@DrawableRes int resourceId) {
    if (isAutoCloneEnabled) {
      return clone().placeholder(resourceId);
    }

    this.placeholderId = resourceId;
    fields |= PLACEHOLDER_ID;

    return selfOrThrowIfLocked();
  }

error(resId)虽然没有用到(产品不让)

也得水一下原文,虽然经常用,但也要温顾一下:

 /**
   * Sets a resource to display if a load fails.
   *
   * @param resourceId The id of the resource to use as a placeholder.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions error(@DrawableRes int resourceId) {
    if (isAutoCloneEnabled) {
      return clone().error(resourceId);
    }
    this.errorId = resourceId;
    fields |= ERROR_ID;

    return selfOrThrowIfLocked();
  }

.dontAnimate()

这个到用的不是特别多,也是刚好碰到这个业务场景要尽量降低渲染耗时:

 /**
   * Disables resource decoders that return animated resources so any resource returned will be
   * static.
   *
   * <p> To disable transitions (fades etc) use
   * {@link com.bumptech.glide.TransitionOptions#dontTransition()}</p>
   */
  // Guaranteed to modify the current object by the isAutoCloneEnabledCheck.
  @SuppressWarnings("CheckResult")
  @NonNull
  @CheckResult
  public RequestOptions dontAnimate() {
    return set(GifOptions.DISABLE_ANIMATION, true);
  }
/**

禁用返回动画资源的资源解码器,因此返回的任何资源都将是静态的。
<p>要禁用过渡效果(淡入淡出等),请使用{@link com.bumptech.glide.TransitionOptions#dontTransition()}</p>
*/ // 通过isAutoCloneEnabledCheck保证修改当前对象。

好像不一定能生效,这个没有亲测是否有实际作用。但还是先禁用比较好。适配几年前旧手机尽可能释放手机性能。

.override(int width, int height)

override(int width, int height) 就很实用了
再回顾一下,后台给笔者的网络图片,唉!重的笔者都看的眼晕:
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP
都是这样的1080 x 1920左右的能直接上2K的大分辨率图片。距离我理想的126 x 224差了何止10倍,粗算一下快100倍了。呃!吐槽一下!
override(int width, int height)原文如下:

/**
   * Overrides the {@link com.bumptech.glide.request.target.Target}'s width and height with the
   * given values. This is useful for thumbnails, and should only be used for other cases when you
   * need a very specific image size.
   *
   * @param width  The width in pixels to use to load the resource.
   * @param height The height in pixels to use to load the resource.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions override(int width, int height) {
    if (isAutoCloneEnabled) {
      return clone().override(width, height);
    }

    this.overrideWidth = width;
    this.overrideHeight = height;
    fields |= OVERRIDE;

    return selfOrThrowIfLocked();
  }
/**

使用给定的值覆盖{@link com.bumptech.glide.request.target.Target}的宽度和高度。这对缩略图很有用,只有在需要非常特定的图像尺寸时才应该使用。

@param width 用于加载资源的像素宽度。

@param height 用于加载资源的像素高度。

@return 此请求构建器。 */ 

本来打算设置成9*16那种的,但是叠加了sizeMultiplier、thumbnail之后那效果太辣眼睛了,不是磨砂而是超级加倍的马赛克效果了。基本轮廓都没了。好吧!这样虽然滑动很丝滑但是太粗暴了,对用户不友好,效果图就不展示了,辣眼睛就让笔者一个人背负吧!于是就有了63 * 2, 112 * 2的设置。同理,别问怎么来的,问就是二分法

.diskCacheStrategy(DiskCacheStrategy.NONE)

这个还是要说明一下的,有一定的作用,但对当前场景作用太微弱了
原文:

/**
   * Sets the {@link DiskCacheStrategy} to use for this load.
   *
   * <p> Defaults to {@link DiskCacheStrategy#AUTOMATIC}. </p>
   *
   * <p> For most applications {@link DiskCacheStrategy#RESOURCE} is
   * ideal. Applications that use the same resource multiple times in multiple sizes and are willing
   * to trade off some speed and disk space in return for lower bandwidth usage may want to consider
   * using {@link DiskCacheStrategy#DATA} or
   * {@link DiskCacheStrategy#ALL}. </p>
   *
   * @param strategy The strategy to use.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions diskCacheStrategy(@NonNull DiskCacheStrategy strategy) {
    if (isAutoCloneEnabled) {
      return clone().diskCacheStrategy(strategy);
    }
    this.diskCacheStrategy = Preconditions.checkNotNull(strategy);
    fields |= DISK_CACHE_STRATEGY;

    return selfOrThrowIfLocked();
  }
/**

设置用于此加载的{@link DiskCacheStrategy}。

<p>默认为{@link DiskCacheStrategy#AUTOMATIC}。</p>
<p>对于大多数应用程序,{@link DiskCacheStrategy#RESOURCE}是理想的。在多个大小的多次使用相同资源的应用程序中,愿意在速度和磁盘空间方面进行一些折衷以换取较低的带宽使用量的应用程序可能希望考虑使用{@link DiskCacheStrategy#DATA}或{@link DiskCacheStrategy#ALL}。</p>
@param strategy 要使用的策略。

@return 此请求构建器。 */

大家都懂蛤!

.onlyRetrieveFromCache(true)

原文:

/**
   *
   * If set to true, will only load an item if found in the cache, and will not fetch from source.
   */
  @NonNull
  @CheckResult
  public RequestOptions onlyRetrieveFromCache(boolean flag) {
    if (isAutoCloneEnabled) {
      return clone().onlyRetrieveFromCache(flag);
    }

    this.onlyRetrieveFromCache = flag;
    fields |= ONLY_RETRIEVE_FROM_CACHE;

    return selfOrThrowIfLocked();
  }

/**

如果设置为true,仅在缓存中找到项目时才会加载,不会从源获取。 
*/

笔者是十分希望用这个的,可惜不能满足场景使用要求,它会直接过滤不在本地二级缓存的图片。不符合场景要求。但加载效果体验很丝滑顺畅的。接近京东首页的体验了。

.skipMemoryCache(true) // 跳过内存缓存

 /**
   * Allows the loaded resource to skip the memory cache.
   *
   * <p> Note - this is not a guarantee. If a request is already pending for this resource and that
   * request is not also skipping the memory cache, the resource will be cached in memory.</p>
   *
   * @param skip True to allow the resource to skip the memory cache.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions skipMemoryCache(boolean skip) {
    if (isAutoCloneEnabled) {
      return clone().skipMemoryCache(true);
    }

    this.isCacheable = !skip;
    fields |= IS_CACHEABLE;

    return selfOrThrowIfLocked();
  }
这个方法用于允许加载的资源跳过内存缓存。

请注意,这并不是一个保证。如果对于该资源已经有一个挂起的请求,并且该请求也没有跳过内存缓存,那么该资源将被缓存在内存中。

@param skip 为true时允许资源跳过内存缓存。
@return 此请求构建器。

某些场景会用到。加深一下印象

.sizeMultiplier(0.85f)

/**
   * Applies a multiplier to the {@link com.bumptech.glide.request.target.Target}'s size before
   * loading the resource. Useful for loading thumbnails or trying to avoid loading huge resources
   * (particularly {@link Bitmap}s on devices with overly dense screens.
   *
   * @param sizeMultiplier The multiplier to apply to the
   *                       {@link com.bumptech.glide.request.target.Target}'s dimensions when
   *                       loading the resource.
   * @return This request builder.
   */
  @NonNull
  @CheckResult
  public RequestOptions sizeMultiplier(@FloatRange(from = 0, to = 1) float sizeMultiplier) {
    if (isAutoCloneEnabled) {
      return clone().sizeMultiplier(sizeMultiplier);
    }

    if (sizeMultiplier < 0f || sizeMultiplier > 1f) {
      throw new IllegalArgumentException("sizeMultiplier must be between 0 and 1");
    }
    this.sizeMultiplier = sizeMultiplier;
    fields |= SIZE_MULTIPLIER;

    return selfOrThrowIfLocked();
  }

/**

在加载资源之前,对{@link com.bumptech.glide.request.target.Target}的大小应用乘数。适用于加载缩略图或尝试避免加载庞大资源(特别是在屏幕密度过大的设备上的{@link Bitmap})。

@param sizeMultiplier 在加载资源时应用于{@link com.bumptech.glide.request.target.Target}尺寸的乘数。

@return 此请求构建器。 */ 

这个十分契合笔者当前也场景,针对那些大而重的网络图片进行处理。

noTransformation()

/**
   * Returns a {@link RequestOptions} object with {@link #dontTransform()} set.
   */
  @SuppressWarnings("WeakerAccess")
  @NonNull
  @CheckResult
  public static RequestOptions noTransformation() {
    if (noTransformOptions == null) {
      noTransformOptions = new RequestOptions()
          .dontTransform()
          .autoClone();
    }
    return noTransformOptions;
  }
/**

返回一个设置了{@link #dontTransform()}的{@link RequestOptions}对象。 */ 

这个和dontAnimate类似,但体验上没有大的提升效果。也许这个设置是有误的。还是要多进行调试

/**
   * Similar to {@link #lock()} except that mutations cause a {@link #clone()} operation to happen
   * before the mutation resulting in all methods returning a new Object and leaving the original
   * locked object unmodified.
   *
   * <p>Auto clone is not retained by cloned objects returned from mutations. The cloned objects
   * are mutable and are not locked.
   */
  @NonNull
  public RequestOptions autoClone() {
    if (isLocked && !isAutoCloneEnabled) {
      throw new IllegalStateException("You cannot auto lock an already locked options object"
          + ", try clone() first");
    }
    isAutoCloneEnabled = true;
    return lock();
  }
/**

与{@link #lock()}类似,不同之处在于在发生突变之前会执行{@link #clone()}操作,导致所有方法返回一个新的对象,原始的锁定对象保持不变。
<p>自动克隆不会被从突变中返回的克隆对象保留。克隆对象是可变的,并且未被锁定。
*/ 

暂时理解不了为啥要克隆,这里没有介绍克隆的使用场景,后续再观察使用情况。

smartApi接口开发工具推荐

历时一年半多开发终于smartApi-v1.0.0版本在2023-09-15晚十点正式上线
smartApi是一款对标国外的postman的api调试开发工具,由于开发人力就作者一个所以人力有限,因此v1.0.0版本功能进行精简,大功能项有:

  • api参数填写
  • api请求响应数据展示
  • PDF形式的分享文档
  • Mock本地化解决方案
  • api列表数据本地化处理
  • 再加上UI方面的打磨

下面是一段smartApi使用介绍:
【Android】画面卡顿优化列表流畅度四之Glide几个常用参数设置-LMLPHP

下载地址:

https://pan.baidu.com/s/1kFAGbsFIk3dDR64NwM5y2A?pwd=csdn

11-14 10:31