Glide主要使用inBitmap和BitmapPool实现内存复用。当设置了Options.inBitmap后,采用Options对象的解码方法生成目标Bitmap时,会尝试复用inBitmap的内存,而inBitmap复用内存存储在BitmapPool中。
当调用Glide.into()会执行DownSampler.setInBitmap()向BitmapPool.getDirty()中传入宽高和格式,得到可复用的对象,实现内存复用
glide/library/src/main/java/com/bumptech/glide/load/resource/bitmap/Downsampler.java
private static void setInBitmap(
BitmapFactory.Options options, BitmapPool bitmapPool, int width, int height) {
@Nullable Bitmap.Config expectedConfig = null;
// Avoid short circuiting, it appears to break on some devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (options.inPreferredConfig == Config.HARDWARE) {
return;
}
// 在 API 26 上,即使图像有效,某些图像的 outConfig 也可能为 null,可以解码并填充
// outWidth/outHeight/outColorSpace
expectedConfig = options.outConfig;
}
if (expectedConfig == null) {
// 我们猜测 BitmapFactory 会返回我们请求的配置。 情况并非总是如此,尽管我们的猜测往往是保守的并且更喜欢更大尺寸的配置
// ,以便位图无论如何都适合我们的图像。 如果我们在这里错了并且我们选择的配置太小,我们的初始解码将失败,但我们将重试没有
// inBitmap 会成功,所以如果我们在这里错了,我们的效率会降低但仍然正确。
expectedConfig = options.inPreferredConfig;
}
// BitmapFactory will clear out the Bitmap before writing to it, so getDirty is safe.
options.inBitmap = bitmapPool.getDirty(width, height, expectedConfig);
}