详细解释强力的图片加载框架 Glide的配置(顺便补充下CollapsingToolbarLayout的一些功能)

来源:互联网 发布:100m网络下载速度 编辑:程序博客网 时间:2024/05/01 15:51

转载请注明出处:王亟亟的大牛之路

折腾了一天,单位里的网终于好了真是蛋疼,然后今天讲Glide(本来是准备昨天写的,唉)

理论性的介绍就直接从网上扣点来了,从头码字没啥意义,废话不多,开始!


理论性的东西可以看 http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0327/2650.html

这篇是Glide和Picasso的对比,分析的蛮不错的

我们来贴下今天的例子

这里写图片描述

上图中所有的图片都是异步下载的,虽然图片本身并不大,但是加载的还是很流畅的。

前面贴的那个传送门已经把大致的文字描述都讲了,那我干什么?

拆Configuration,常规使用Glide只需要
Glide.with(this).load(Config.IMAGE_URL).into(imageView);,但是在自己的实际场景下可能会有一些自定义的定制,那么就需要搞一个想ImageLoader里Application类里干的活了。

Starting in Glide 3.5, you can use the GlideModule interface to lazily configure Glide and register components like ModelLoaders automatically when the first Glide request is made.

从Glide3.5版本开始,你可以使用GlideModule接口来惰性的初始化以及声明组件,当第一次加载请求出现时。

那么要如何使用呢?

实现GlideModule,像这样。

public class GlideModuleConfig implements GlideModule {    //在这里创建设置内容,之前文章所提及的图片质量就可以在这里设置    //还可以设置缓存池参数什么的    @Override    public void applyOptions(Context context, GlideBuilder builder) {     builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);    }    //在这里注册ModelLoaders    //可以在这里清除缓存什么的    @Override    public void registerComponents(Context context, Glide glide) {    glide.clearDiskCache();    }}

然后在我们的AndroidManifest.xml文件里添加我们这个模块
像这样

 <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <meta-data            android:name="sample.wjj.glidedemo.GlideModuleConfig"            android:value="GlideModule" />        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>

Glide是允许多个设置Model的所以必然会有冲突(如果有多个lib项目的话),可以使用

<meta-data android:name=”sample.wjj.glidedemo.GlideModuleConfig” tools:node=”remove” />来避免这一类的问题

Disk Cache

You can use the GlideBuilder’s setDiskCache() method to set the location and/or maximum size of the disk cache. You can also disable the cache entirely using DiskCacheAdapter or replace it with your own implementation of the DiskCache interface. Disk caches are built on background threads to avoid strict mode violations using the DiskCache.Factory interface.

你可以使用GlideBuilder的setDiskCache() 方法来设置储存位置以及一些储存空间的大小.你也可以选择经禁用或者写自己的实现。磁盘高速缓存是在后台线程实现的,它使用的是DiskCache.Factory接口

Size

By default Glide uses the InternalCacheDiskCacheFactory class to build disk caches. The internal cache factory places the disk cache in your application’s internal cache directory and sets a maximum size of 250MB. Using the cache directory rather than the external SD card means no other applications will be able to access the images you download. See Android’s Storage Options doc for more details.

这一串好长,我点名重点。 默认储存在应用程序内部,而非SD卡等外部目录,这样其他程序也就无法访问缓存的内容了,默认最大尺寸为250M。

默认在这:
int DEFAULT_DISK_CACHE_SIZE = 250 * 1024 * 1024;
String DEFAULT_DISK_CACHE_DIR = "image_manager_disk_cache";

那么我们如何设置自己的“工厂值”呢?

   builder.setDiskCache( new InternalCacheDiskCacheFactory(context,100*1024*1024));

Location

那如果我们不想存在内存里想存在SD卡可以吗?

 builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, "MY_CACHE_LOCATION", 100 * 1024 * 1024));需要传入3个参数context对象,缓存的路径名称,缓存大小

他其实是在SDCard/Android/data/你的应用包名/cache/目录建了一个缓存的路径名称的文件夹来存放你的缓存内容。

Memory caches and pools

Size

Default sizes are determined by the MemorySizeCalculator class. The MemorySizeCalculator class takes into account the screen size available memory of a given device to come up with reasonable default sizes. You can construct your own instance if you want to adjust Glide’s defaults:

默认情况下缓存内容的尺寸是MemorySizeCalculator这个类来控制的,那么如何控制?根据所需控件大小来缓存(也就是传送门文章里写道的根据ImageView的大小来储存图片),同样的如果你想自己自定义那么就自己实现

MemorySizeCalculator calculator = new MemorySizeCalculator(context);int defaultMemoryCacheSize = calculator.getMemoryCacheSize();int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

当你在使用的过程中对某个阶段的内存有特殊操作,你可以这样

在registerComponents方法里作如下操作。

 glide.setMemoryCategory(MemoryCategory.HIGH);

他有预设的一些枚举值,你可以根据需要来选择(也就是放大缩小之类的操作,这里指的是内存缓存部分和图片池)

/**     * Tells Glide's memory cache and bitmap pool to use at most half of their initial maximum size.     */    LOW(0.5f),    /**     * Tells Glide's memory cache and bitmap pool to use at most their initial maximum size.     */    NORMAL(1f),    /**     * Tells Glide's memory cache and bitmap pool to use at most one and a half times their initial maximum size.     */    HIGH(1.5f);

Memory Cache

Glide’s memory cache is used to hold resources in memory so that they are instantly available without having to perform I/O.

Glide’s的内存缓存都是储存在内存中的使他们可以立即被使用,而不是必须走IO操作区读写

You can use GlideBuilder’s setMemoryCache() method to set the size and/or implementation you wish to use for your memory cache. The LruResourceCache class is Glide’s default implementation. You can set a custom maximum in memory byte size by passing in the size you want to the LruResourceCache constructor:

这一段也很啰嗦,反正就是告诉我们可以用LruResourceCache这个类来自定义内存的最大使用字节(看到这里很多小伙伴有疑虑,为什么会有2个所谓的内存空间,简单的说就是 一个是你来放的容器,一个是拿来快速用的)

builder.setMemoryCache(new LruResourceCache(100*1024*1024));

Bitmap Pool

Glide’s bitmap pool is used to allow Bitmaps of a variety of different sizes to be re-used which can substantially reduce jank inducing garbage collections caused by pixel array allocations while images are being decoded.

白话解释下,图片池允许各种各样不同尺寸的图片被重新使用,反正就是按照控件大小来操作,可以将大大减少垃圾图片的存在,同时由于像素阵列分配而图像被解码操作

You can use GlideBuilder’s setBitmapPool() method to set the size and/or implementation of the bitmap pool. The LruBitmapPool class is Glide’s default implementation. The LruBitmapPool class uses an LRU algorithm to retain the most recently used sizes of Bitmaps. You can set a custom maximum in memory byte size by passing the size you want to the LruBitmapPool constructor:

这一段反正意思就是你也可以setBitmapPool来自定义图片池的大小,像这样

builder.setBitmapPool(new LruBitmapPool(200*1024*1024));

Bitmap Format

The GlideBuilder class also allows you to set a global default for the preferred Bitmap configuration for your application.

By default Glide prefers RGB_565 because it requires only two bytes
per pixel (16 bit) and therefore has half the memory footprint of the
higher quality and system default ARGB_8888. RGB_565 however can have
issues with banding in certain images and also does not support
transparency.

If banding is a problem in your application and/or you want the
highest possible image quality, you can use GlideBuilder’s
setDecodeFormat method to set DecodeFormat.ALWAYS_ARGB_8888 as Glide’s
preferred Bitmap configuration:

builder.setDecodeFormat(DecodeFormat.ALWAYS_ARGB_8888);

这部分在传送门里有提到,不翻译不解释了,打了那么多手累了。

总结:简单易用功能强大,性能好,速度快,很推荐

配置也比隔壁老王方便

git:https://github.com/bumptech/glide


接下来再补充个小知识点

上次提到的MD的dialog中提到了CollapsingToolbarLayout然后有有些小伙伴文怎么把那一坨颜色变成图片什么的,那我也就实现了下,效果是这样

这里写图片描述

然后收起来之后本身透明的toolbar也变成了绿色,本来绿色的CollapsingToolbarLayout的背景变成了图片,那这是怎么做的呢?

 <android.support.design.widget.CollapsingToolbarLayout            android:id="@+id/toolbar_layout"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:background="@drawable/gee"            android:fitsSystemWindows="true"            app:contentScrim="@color/dialogColor"            app:expandedTitleMarginBottom="70dp"            app:expandedTitleMarginEnd="64dp"            app:expandedTitleMarginStart="48dp"            app:layout_scrollFlags="scroll|exitUntilCollapsed"            app:title="尝试效果">

contentScrim 设置当完全CollapsingToolbarLayout折叠(收缩)后的背景颜色(就是这么变绿的)

然后我暂时没有找到标签里有设置Title颜色的操作,但是java方法倒是有

类里面声明对象

 CollapsingToolbarLayout toolbar_layout;

onCreate里面find一下,然后set一下就好。

  toolbar_layout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);        toolbar_layout.setExpandedTitleColor(getResources().getColor(R.color.dialogColor));

不太推荐大家该一个imageview进去然后再插textview什么的 毕竟有android:background="@drawable/gee"为什么不用呢?

源码地址:https://github.com/ddwhan0123/BlogSample/blob/master/GlideDemo.zip

6 0
原创粉丝点击