Android BitmapDrawable()的使用

查看源码BitmapDrawable.javaBitmapDrawable有若干个构造方法。

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),不同的是前者传入一个ResourcesNULL值,后者传入了一个非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确定一个正确的密度(S4480)。否则会采用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);

 

总结,因为两个构造方法参数不同,得到两个不同的宽高值,于是在绘制中就出现界面异常。(具体为什么算出来的Widthheight差异很大还需要继续调查,有兴趣的可以再查查)

原文地址:https://www.cnblogs.com/lechance/p/4373168.html