Skip to content

Coding(7): Glide使用及注意的地方

clarkehe edited this page Sep 3, 2016 · 6 revisions

实现图片加载的库有很多,用过其中两个:UniversalImageLoader和Glide。UniversalImageLoader用的时候没有太深入了解,对Glide有过一点研究,对其大概原理及要注意的地方大概说下。

要实现一个图片加载库,大概要包括这个几功能模块:资源文件下载、资源解码、资源缓存。Glide除这三个功能外,还有一些挺智能的特性。

文件下载

资源解码

内存缓存

磁盘缓存

Bitmap池
从Bitmap池取缓存,是根据图片尺寸来取的,config一般都是一样的。关于尺寸,要注意下,会有两个尺寸:图片原始尺寸,使用尺寸(也就是ImageView的大小)。这里的尺寸应该是使用尺寸。

    @Override
    public synchronized Bitmap get(int width, int height, Bitmap.Config config) {
        Bitmap result = getDirty(width, height, config);
        if (result != null) {
            // Bitmaps in the pool contain random data that in some cases must be cleared for an image to be rendered
            // correctly. we shouldn't force all consumers to independently erase the contents individually, so we do so
            // here. See issue #131.
            result.eraseColor(Color.TRANSPARENT);
        }
        return result;
    }

要点1:从理论上讲,图片的使用的尺寸越统一,Bitmap池命中率应该是越高。

要点2:如果在xml中ImageView的宽高设置为wrap_content,在取缓存时,宽高值为手机的分辨率;在保存缓存时,宽高为图片实际大小。ImageView宽高设置为wrap_content时从bitmap池取缓存,会取不到。因此,尽量给ImageView设置一个大小,或在Glide接口中提供大小。

Bitmap池中的Bitmap都是不再使用的(可以被回收,不影响功能),内存缓存中的Bitmap也是一样,如何判断Bitmap不再使用了呢?

    @Override
    public synchronized boolean put(Bitmap bitmap) {
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        Log.d(TAG, "put, width:" + width + ",height:" + height);
        return super.put(bitmap);
    }

要点1:当回收Bitmap时,首先考虑放到内存缓存,供下次复用。如果内存缓存空间不够,则会按照LRU规则淘汰一些放到Bitmap池,如果Bitmap池空间不够,就回收了,释放内存。

要点2:

【参考资料】
Glide 系列预览
[Android] Glide 图片缓存机制
Google推荐的图片加载库Glide介绍

Clone this wiki locally