你真的理解Bitmap么酿傍?
一直以來烙懦,Android適配要將圖片放在mdpi、hdpi赤炒、xhdpi氯析,如果放亂了就會(huì)導(dǎo)致各種性能問題亏较,為什么?為什么我講圖片放在mdpi,然后運(yùn)行到hdpi設(shè)備上圖片會(huì)大很多掩缓?源碼怎么處理呢雪情?俗話說,要知其然也要知其所以然
res文件的加載
我們先來看一段偽代碼
Bitmap bm = BitmapFactory.decodeResource(res,R.mipmap.icon);
imageView.setImageBitmap(bm);
- 假設(shè):icon是放在mipmap-mdpi目錄下你辣,然后我運(yùn)行的目標(biāo)設(shè)備是hdpi分辨率巡通,接下來我們來追蹤下流程
BitmapFactory.decodeResource
public static Bitmap decodeResource(Resources res, int id, Options opts) {
Bitmap bm = null;
InputStream is = null;
try {
final TypedValue value = new TypedValue();
is = res.openRawResource(id, value);
bm = decodeResourceStream(res, value, is, null, opts);
} catch (Exception e) {
...
} finally {
...
}
...
return bm;
}
- BitmapFactory.decodeResource有兩個(gè)重載方法,實(shí)際上最終調(diào)用的是上面這個(gè)函數(shù)
- 這個(gè)函數(shù)中绢记,首先初始化了一個(gè)TypeValue實(shí)力扁达,然后通過res,進(jìn)一步通過Native層的AssetManager讀到icon流蠢熄,對(duì)應(yīng)的實(shí)現(xiàn)AssetInputStream
- 流程代碼如下:
Resources.openRawResource
public InputStream openRawResource(@RawRes int id, TypedValue value)
throws NotFoundException {
getValue(id, value, true);
try {
return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
AssetManager.ACCESS_STREAMING);
} catch (Exception e) {
...
}
}
AssetManager.openNonAsset
public final InputStream openNonAsset(int cookie, String fileName, int accessMode)
throws IOException {
synchronized (this) {
...
long asset = openNonAssetNative(cookie, fileName, accessMode);
if (asset != 0) {
AssetInputStream res = new AssetInputStream(asset);
incRefsLocked(res.hashCode());
return res;
}
}
...
}
- 這里不在細(xì)說AssetManager的工作機(jī)制跪解,如果你感興趣請(qǐng)看這里
BitmapFactory.decodeResourceStream
public static Bitmap decodeResourceStream(Resources res, TypedValue value,
InputStream is, Rect pad, Options opts) {
if (opts == null) {
opts = new Options();
}
if (opts.inDensity == 0 && value != null) {
final int density = value.density;
if (density == TypedValue.DENSITY_DEFAULT) {
opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
} else if (density != TypedValue.DENSITY_NONE) {
opts.inDensity = density;
}
}
if (opts.inTargetDensity == 0 && res != null) {
opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
}
return decodeStream(is, pad, opts);
}
- 參數(shù)中,is的實(shí)際就是讀icon文件的流签孔,value就是mdpi文件對(duì)應(yīng)的信息叉讥,所以執(zhí)行完這個(gè)方法后,opts存儲(chǔ)的inDensity指向的是mdpi饥追,inTargetDensity指向的是目標(biāo)設(shè)備的也就是hdpi的图仓,接著往下看代碼
BitmapFactory.decodeStream
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
...
Bitmap bm = null;
...
try {
if (is instanceof AssetManager.AssetInputStream) {
final long asset =
((AssetManager.AssetInputStream) is).getNativeAsset();
bm = nativeDecodeAsset(asset, outPadding, opts);
} else {
...
}
...
setDensityFromOptions(bm, opts);
} finally {
...
}
return bm;
- is是前面AssetManager.openNonAsset返回的,類型是AssetInputStream但绕,所以會(huì)在native層去解析asset,
- native層的代碼調(diào)用邏輯為BitmaFactory.cpp,其全路徑為android / platform / frameworks / base / core / jni / android / graphics / BitmapFactory.cpp
static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jint native_asset,
jobject padding, jobject options) {
return nativeDecodeAssetScaled(env, clazz, native_asset, padding, options, false, 1.0f);
}
static jobject nativeDecodeAssetScaled(JNIEnv* env, jobject clazz, jint native_asset,
jobject padding, jobject options, jboolean applyScale, jfloat scale) {
SkStream* stream;
Asset* asset = reinterpret_cast<Asset*>(native_asset);
bool forcePurgeable = optionsPurgeable(env, options);
if (forcePurgeable) {
....
stream = copyAssetToStream(asset);
...
} else {
...
stream = new AssetStreamAdaptor(asset);
}
SkAutoUnref aur(stream);
return doDecode(env, stream, padding, options, true, forcePurgeable, applyScale, scale);
}
- 可以看到最終調(diào)用到了doDecode方法
static jobject doDecode(JNIEnv* env, SkStream* stream, jobject padding,
jobject options, bool allowPurgeable, bool forcePurgeable = false,
bool applyScale = false, float scale = 1.0f) {
int sampleSize = 1;
...
jobject javaBitmap = NULL;
if (options != NULL) {
sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
...
javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
}
...
if (willScale) {
...
const float sx = scaledWidth / float(decoded->width());
const float sy = scaledHeight / float(decoded->height());
bitmap->setConfig(decoded->getConfig(), scaledWidth, scaledHeight);
bitmap->allocPixels(&javaAllocator, NULL);
bitmap->eraseColor(0);
SkPaint paint;
paint.setFilterBitmap(true);
SkCanvas canvas(*bitmap);
canvas.scale(sx, sy);
canvas.drawBitmap(*decoded, 0.0f, 0.0f, &paint);
}
...
if (javaBitmap != NULL) {
// If a java bitmap was passed in for reuse, pass it back
return javaBitmap;
}
// now create the java bitmap
return GraphicsJNI::createBitmap(env, bitmap, javaAllocator.getStorageObj(),
isMutable, ninePatchChunk);
}
- 略去中間我不管興趣的代碼(ps:如果你對(duì)Bitmap解析過程中各項(xiàng)參數(shù)感興趣救崔,可以看下這個(gè)類)
- 我發(fā)現(xiàn)在native層分別時(shí)候,并沒有去做縮放捏顺,那么我一開始提出的縮放點(diǎn)在哪里呢六孵?先保留這個(gè)疑問繼續(xù)往下看
BitmapFactory.setDensityFromOptions
private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
...
final int density = opts.inDensity;
if (density != 0) {
outputBitmap.setDensity(density);
final int targetDensity = opts.inTargetDensity;
if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
return;
}
byte[] np = outputBitmap.getNinePatchChunk();
final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
if (opts.inScaled || isNinePatch) {
outputBitmap.setDensity(targetDensity);
}
} else if (opts.inBitmap != null) {
...
}
}
- 在BitmapFactory.setDensityFromOptions中,把前面對(duì)應(yīng)解析到的opts.inDensity傳給了解析完的bitmap幅骄,那么是不是說在使用這個(gè)bitmap 時(shí)候再去進(jìn)行縮放呢劫窒?
- 查看Options針對(duì)inDensity、inTargetDensity的解釋拆座,證明我的猜想是正確的
/**
* The pixel density to use for the bitmap. This will always result
* in the returned bitmap having a density set for it (see
* {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}). In addition,
* if {@link #inScaled} is set (which it is by default} and this
* density does not match {@link #inTargetDensity}, then the bitmap
* will be scaled to the target density before being returned.
*
*/
public int inDensity;
/**
* The pixel density of the destination this bitmap will be drawn to.
* This is used in conjunction with {@link #inDensity} and
* {@link #inScaled} to determine if and how to scale the bitmap before
* returning it.
*/
public int inTargetDensity;
- 上面不進(jìn)行翻譯主巍,我覺得會(huì)曲解意思,意思就是說在繪制時(shí)候挪凑,如果inDensity孕索、inTargetDensity不一致那么就會(huì)按照inTargetDensity的值進(jìn)行縮放
- 回到一開始的偽代碼,接下老我們看ImageView是如何處理的
ImageView.onDraw
- 熟悉Android開發(fā)的一定知道躏碳,調(diào)用setImageBitmap會(huì)調(diào)用invalidate搞旭,之后的流程不再細(xì)說,最后我們來看onDraw都做了什么
protected void onDraw(Canvas canvas) {
...
mDrawable.draw(canvas);
...
}
- 略去不關(guān)心的代碼,實(shí)際上onDraw就只調(diào)用了一行代碼
- mDrawable是什么选脊?他的draw方法都做了什么杭抠?
ImageView.setImageBitmap
public void setImageBitmap(Bitmap bm) {
...
mRecycleableBitmapDrawable = new ImageViewBitmapDrawable(
mContext.getResources(), bm);
...
}
- 實(shí)際上在setImageBitmap時(shí)候,會(huì)創(chuàng)建一個(gè)ImageViewBitmapDrawable恳啥,他的父類是BitmapDrawable偏灿,后續(xù)代碼流程會(huì)將這個(gè)ImageViewBitmapDrawable賦值給mDrawable
- 我們來看BitmapDrawable.draw都干嘛了
BitmapDrawable.draw
public void draw(Canvas canvas) {
...
canvas.drawBitmap(bitmap, null, mDstRect, paint);
...
}
- 這里會(huì)調(diào)用到canvas.drawBitmap,接著追下去
canvas.drawBitmap
public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst,
@Nullable Paint paint) {
...
native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom,
dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity,
bitmap.mDensity);
}
- 最終調(diào)用的是native_drawBitmap钝的,并且注意一個(gè)參數(shù)bitmap.mDensity
- 接著往下追蹤翁垂,Canvas.cpp的位置是android / platform / frameworks / core / jni / android / graphics / Canvas.cpp
{"native_drawBitmap","(IIFFIIII)V",
(void*) SkCanvasGlue::drawBitmap__BitmapFFPaint},
{"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/RectF;III)V",
(void*) SkCanvasGlue::drawBitmapRF},
{"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/Rect;III)V",
(void*) SkCanvasGlue::drawBitmapRR},
{"native_drawBitmap", "(I[IIIFFIIZI)V",
- 對(duì)應(yīng)的映射有4處,drawBitmap__BitmapFFPaint查看這個(gè)實(shí)現(xiàn)如下:
static void drawBitmap__BitmapFFPaint(JNIEnv* env, jobject jcanvas,
SkCanvas* canvas, SkBitmap* bitmap,
jfloat left, jfloat top,
SkPaint* paint, jint canvasDensity,
jint screenDensity, jint bitmapDensity) {
...
if (canvasDensity == bitmapDensity || canvasDensity == 0
|| bitmapDensity == 0) {
...
} else {
canvas->save();
SkScalar scale = SkFloatToScalar(canvasDensity / (float)bitmapDensity);
canvas->translate(left_, top_);
canvas->scale(scale, scale);
...
filteredPaint.setFilterBitmap(true);
canvas->drawBitmap(*bitmap, 0, 0, &filteredPaint);
canvas->restore();
}
}
- 這里硝桩,如果說canvasDensity與bitmapDensity不一致就會(huì)進(jìn)行縮放沿猜,
- 所以我們可以得出結(jié)論,mdpi下的icon在hdpi中對(duì)應(yīng)的大小是whargb*TargetDensity/inDensity
- 驗(yàn)證了我們開篇回答的問題碗脊,over到此可以愉快的寫bug去了