你真的理解Bitmap么?

你真的理解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去了
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蛛枚,一起剝皮案震驚了整個(gè)濱河市顾画,隨后出現(xiàn)的幾起案子内斯,更是在濱河造成了極大的恐慌叨咖,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件矢劲,死亡現(xiàn)場(chǎng)離奇詭異赦拘,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)芬沉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門躺同,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人丸逸,你說我怎么就攤上這事蹋艺。” “怎么了椭员?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵车海,是天一觀的道長(zhǎng)笛园。 經(jīng)常有香客問我隘击,道長(zhǎng),這世上最難降的妖魔是什么研铆? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任埋同,我火速辦了婚禮,結(jié)果婚禮上棵红,老公的妹妹穿的比我還像新娘凶赁。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布虱肄。 她就那樣靜靜地躺著致板,像睡著了一般。 火紅的嫁衣襯著肌膚如雪咏窿。 梳的紋絲不亂的頭發(fā)上斟或,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音集嵌,去河邊找鬼萝挤。 笑死,一個(gè)胖子當(dāng)著我的面吹牛根欧,可吹牛的內(nèi)容都是我干的怜珍。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼凤粗,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼酥泛!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嫌拣,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤揭璃,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后亭罪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體瘦馍,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年应役,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了情组。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡箩祥,死狀恐怖院崇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情袍祖,我是刑警寧澤底瓣,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站蕉陋,受9級(jí)特大地震影響捐凭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜凳鬓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一茁肠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧缩举,春花似錦垦梆、人聲如沸匹颤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)印蓖。三九已至,卻和暖如春京腥,著一層夾襖步出監(jiān)牢的瞬間另伍,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工绞旅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留摆尝,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓因悲,卻偏偏與公主長(zhǎng)得像堕汞,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子晃琳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容