Android BitmapDrawable()的使用,bitmapdrawable
查看源碼BitmapDrawable.java。BitmapDrawable有若干個構造方法。
New BitmapDrawable(Bitmap bitmap)是早期的一個構造方法,在android 4.0已經過時,部分代碼如下:
this(new BitmapState(bitmap), null);
而google提倡使用new BitmapDrawable(Bitmap bitmap,Resources res),其部分代碼如下:
this(new BitmapState(bitmap), res);
可見以上兩個方法均調用了一個私人的方法: BitmapDrawable(BitmapState state, Resources res),不同的是前者傳入一個Resources的NULL值,後者傳入了一個非NULL值。在BitmapDrawable(BitmapState state, Resources res)方法中部分代碼如下:
if (res != null) {
mTargetDensity = res.getDisplayMetrics().densityDpi;// BitmapDrawable(Bitmap,Resources ) go here
} else {
mTargetDensity = state.mTargetDensity; // BitmapDrawable(Bitmap) go here
}
看來當前BitmapDrawable是儲存一個目標密度,這個密度如果傳入了Resources對象,會根據Resources確定一個正確的密度(S4為480)。否則會採用BitmapState的目標密度,而它的目標密度會有一個預設值:
int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
再查看DisplayMetrics.java源碼,有如下定義:
public static final int DENSITY_DEFAULT = DENSITY_MEDIUM;//這個值為240
總上所述,在S4 ,new BitmapDrawable(Bitmap)得到了一個240的目標密度。而new BitmapDrawable(Bitmap bitmap,Resources res)得到一個480的目標密度。當計算Bitmap的寬高有:
mBitmapWidth = mBitmap.getScaledWidth(mTargetDensity);
mBitmapHeight = mBitmap.getScaledHeight(mTargetDensity);
總結,因為兩個構造方法參數不同,得到兩個不同的寬高值,於是在繪製中就出現介面異常。(具體為什麼算出來的Width和height差異很大還需要繼續調查,有興趣的可以再查查)