今天使用LruCache寫demo的時候,要獲取Bitmap的大小
於是就用到了
return bitmap.getRowBytes() * bitmap.getHeight();// 獲取大小並返回
//Bitmap所占用的內存空間數等於Bitmap的每一行所占用的空間數乘以Bitmap的行數
為什么不用bitmap.getByteCount()呢?
因為getByteCount要求的API版本較高,考慮到兼容性使用上面的方法
1、getRowBytes:Since API Level 1
2、getByteCount:Since API Level 12
查看Bitmap源碼
- public final int getByteCount() {
- return getRowBytes() * getHeight();
- }
所以API 12 以后
getByteCount() = getRowBytes() * getHeight();
在計算Bitmap所占空間時上面的方法或許有幫助。
補充:
- /**
- * 得到bitmap的大小
- */
- public static int getBitmapSize(Bitmap bitmap) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //API 19
- return bitmap.getAllocationByteCount();
- }
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
- return bitmap.getByteCount();
- }
- // 在低版本中用一行的字節x高度
- return bitmap.getRowBytes() * bitmap.getHeight(); //earlier version
- }