如果您确定所需的大小,自己缩放位图将节省内存,因为 android 不会这样做,至少不是您期望的方式(参见底部的编辑和 cmets)。
我认为您还需要做一些其他的考虑。当您自己解码位图时,您的目标是一个大小,可能是ImageView 的大小(因此在计算出ImageView 的大小之后)。膨胀 xml 时,该大小尚不清楚。如果解码Bitmap 后ImageView 的大小发生变化,会发生什么情况?你会重新调整它吗?在这种情况下,解码更大的Bitmap 然后只缩放绘图不是更有效吗?
找出android是否正在缩放Bitmap的一种方法非常简单,尝试在xml中设置一个可笑的大图像作为src,看看会发生什么(剧透警报,它会爆炸)。
深入源码,看来ImageView的src的Bitmap是在Drawable类的这个方法中解码的,貌似没有考虑大小,只考虑屏幕密度
public static Drawable createFromResourceStream(Resources res, TypedValue value,
InputStream is, String srcName, BitmapFactory.Options opts) {
if (is == null) {
return null;
}
/* ugh. The decodeStream contract is that we have already allocated
the pad rect, but if the bitmap does not had a ninepatch chunk,
then the pad will be ignored. If we could change this to lazily
alloc/assign the rect, we could avoid the GC churn of making new
Rects only to drop them on the floor.
*/
Rect pad = new Rect();
// Special stuff for compatibility mode: if the target density is not
// the same as the display density, but the resource -is- the same as
// the display density, then don't scale it down to the target density.
// This allows us to load the system's density-correct resources into
// an application in compatibility mode, without scaling those down
// to the compatibility density only to have them scaled back up when
// drawn to the screen.
if (opts == null) opts = new BitmapFactory.Options();
opts.inScreenDensity = Drawable.resolveDensity(res, 0);
Bitmap bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
if (bm != null) {
byte[] np = bm.getNinePatchChunk();
if (np == null || !NinePatch.isNinePatchChunk(np)) {
np = null;
pad = null;
}
final Rect opticalInsets = new Rect();
bm.getOpticalInsets(opticalInsets);
return drawableFromBitmap(res, bm, np, pad, opticalInsets, srcName);
}
return null;
}
另外,在BitmapDrawable 的draw(Canvas canvas) 方法中,绘图是用这条线完成的:
canvas.drawBitmap(bitmap, null, mDstRect, paint);
看起来Bitmap 按原样使用,它是目标Rect 进行缩放
编辑
今天我也无意中发现了另一个有趣的事情,我在drawable文件夹中放了一张图片(未指定密度),并检索到一个带有BitmapFactory.decodeResourceStream(res, value, is, pad, opts)的Bitmap,和上面的一样。我得到的位图比可绘制文件夹中的图像大得多,我认为如果未指定密度,它将假定为 mdpi,甚至会对位图进行上采样以获得更高的目标密度。