基础
- Drawable:
一切可 draw 对象。图像肯定是可绘制的,对应的 Drawable 就是 BitmapDrawable。 - Bitmap:
图片在内存中的表示,它存储了图片的所有信息。
BitmapDrawable
一般会使用 resources.getDrawable(R.drawable.tt) 去获取指定资源对应的 Drawable,返回一个 BitmapDrawable 对象,整个过程中会调用 BitmapFactory 生成一个新的 Bitmap。
在整个流程中需要经过 ImageDecoder#decodeDrawable()
public static Drawable decodeDrawable(@NonNull Source src,
@Nullable OnHeaderDecodedListener listener) throws IOException {
Bitmap bitmap = decodeBitmap(src, listener);
return new BitmapDrawable(src.getResources(), bitmap);
}
public static Bitmap decodeBitmap(@NonNull Source src,
@Nullable OnHeaderDecodedListener listener) throws IOException {
TypedValue value = new TypedValue();
value.density = src.getDensity();
ImageDecoder decoder = src.createImageDecoder();
if (listener != null) {
listener.onHeaderDecoded(decoder, new ImageInfo(decoder), src);
}
// 通过 BitmapFactory 将资源解析成一个新的 Bitmap
return BitmapFactory.decodeResourceStream(src.getResources(), value,
((InputStreamSource) src).mInputStream, decoder.mOutPaddingRect, null);
}
整个流程如下:
xml 属性中的 bitmap
在 xml 中使用图片资源,
同一个资源在系统中只对应一个 bitmap
- 在 xml 中使用过的资源,通过 getDrawable() 获取时,指向同一个 bitmap
- 不同 xml 中使用的相同资源,也是同一个 bitmap
ImageView src 属性
ImageView 解析 src 主要通过下面代码完成,可以看到它也是通过 getDrawable() 拿到 BitmapDrawable 对象,所以 也会根据 src 生成新的 bitmap,如果一个图片在 xml 中多次使用,就会被加载多次。
final Drawable d = a.getDrawable(R.styleable.ImageView_src);
background 属性
在 xml 中配置 background 最终也会被解析成 BitmapDrawable,所以 background 会将同一个资源加载成不同的 bitmap