Android View如何加載drawable資源

Android開發(fā)時難免會遇到圖片加載的問題蝎毡,簡單的做法就是把問題丟給圖片框架處理娱颊,幾個主流的圖片框架各有特色申窘,這里也不展開說耕腾,今天突然想了解一下Android圖片資源的加載,主要是想?yún)⒖家幌屡詈猓瑅iew是如何加載drawable的喻杈,因為我們可以直接在UI線程直接設(shè)置view的背景res,如果這個資源圖很大會不會導(dǎo)致ANR或者OOM狰晚?
首先從View.setBackgroundResource(int resid)開始:

    public void setBackgroundResource(@DrawableRes int resid) {
        if (resid != 0 && resid == mBackgroundResource) {
            return;
        }

        Drawable d = null;
        if (resid != 0) {
            d = mContext.getDrawable(resid);
        }
        setBackground(d);

        mBackgroundResource = resid;
    }

顯然筒饰,如果是設(shè)置當前的資源ID,則不會處理壁晒。這里直接通過mContext.getDrawable(resid)獲取drawable瓷们,然后設(shè)置為background,看來這里并不是異步加載圖片的秒咐,如果是大圖時會不會導(dǎo)致ANR呢谬晕?
我們接著看:

    public final Drawable getDrawable(@DrawableRes int id) {
        return getResources().getDrawable(id, getTheme());
    }

ResourcesImpl.java

    Drawable loadDrawable(Resources wrapper, TypedValue value, int id, Resources.Theme theme,
            boolean useCache) throws NotFoundException {
        try {
            final boolean isColorDrawable;
            final DrawableCache caches;
            final long key;
            if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
                    && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
                isColorDrawable = true;
                caches = mColorDrawableCache;
                key = value.data;
            } else {
                isColorDrawable = false;
                caches = mDrawableCache;
                key = (((long) value.assetCookie) << 32) | value.data;
            }

            // First, check whether we have a cached version of this drawable
            // that was inflated against the specified theme. Skip the cache if
            // we're currently preloading or we're not using the cache.
            if (!mPreloading && useCache) {
                final Drawable cachedDrawable = caches.getInstance(key, wrapper, theme);
                if (cachedDrawable != null) {
                    return cachedDrawable;
                }
            }

            // Next, check preloaded drawables. Preloaded drawables may contain
            // unresolved theme attributes.
            final Drawable.ConstantState cs;
            if (isColorDrawable) {
                cs = sPreloadedColorDrawables.get(key);
            } else {
                cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
            }

            Drawable dr;
            if (cs != null) {
                dr = cs.newDrawable(wrapper);
            } else if (isColorDrawable) {
                dr = new ColorDrawable(value.data);
            } else {
                dr = loadDrawableForCookie(wrapper, value, id, null);
            }

            ...

            return dr;
        } catch (Exception e) {
            ...
        }
    }

這個方法加載drawable時,先判斷是否有緩存反镇,有緩存則直接返回緩存的drawable固蚤。這里也區(qū)分了isColorDrawable,并且緩存也是分開的歹茶。下面我們就看看loadDrawableForCookie(wrapper, value, id, null);如何加載Drawable的夕玩。

    private Drawable loadDrawableForCookie(Resources wrapper, TypedValue value, int id, Resources.Theme theme) {
        final String file = value.string.toString();

        final Drawable dr;
        try {
            if (file.endsWith(".xml")) {
                final XmlResourceParser rp = loadXmlResourceParser(
                        file, id, value.assetCookie, "drawable");
                dr = Drawable.createFromXml(wrapper, rp, theme);
                rp.close();
            } else {
                final InputStream is = mAssets.openNonAsset(
                        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
                dr = Drawable.createFromResourceStream(wrapper, value, is, file, null);
                is.close();
            }
        } catch (Exception e) {
            ...
        }

        return dr;
    }

這里區(qū)分了需要加載的文件是xml還是圖片文件,如果是xml則直接丟給XmlResourceParser惊豺,若是圖片文件燎孟,則是通過mAssets.openNonAsset()得到一個InputStream,然后將InputStream轉(zhuǎn)為Drawable尸昧。這里的AssetManager.openNonAsset()是native方法揩页,而這里恰恰是可能產(chǎn)生ANR的地方,猜想之所以采用native實現(xiàn)烹俗,就是防止ANR吧爆侣。沒有繼續(xù)看native方法,暫且認為這樣加載圖片不會產(chǎn)生ANR吧幢妄。
繼續(xù)往下兔仰,看看Drawable是如何將InputStream轉(zhuǎn)為Drawable的:

    public static Drawable createFromResourceStream(Resources res, TypedValue value, InputStream is, String srcName, BitmapFactory.Options opts) {
        Rect pad = new Rect();

        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;
    }
    
    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np, Rect pad, Rect layoutBounds, String srcName) {
        if (np != null) {
            return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
        }

        return new BitmapDrawable(res, bm);
    }

最終還是調(diào)用的BitmapFactory.decodeResourceStream,但是上面一句:

opts.inScreenDensity = Drawable.resolveDensity(res, 0);

這里是設(shè)置屏幕密度蕉鸳,也就是這里會更加屏幕密度來加載圖片乎赴,所以資源圖片放錯位置忍法,或者太大也是會導(dǎo)致OOM的。參考郭神的 Android drawable微技巧榕吼,你所不知道的drawable的那些細節(jié)饿序。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市羹蚣,隨后出現(xiàn)的幾起案子原探,更是在濱河造成了極大的恐慌,老刑警劉巖度宦,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件踢匣,死亡現(xiàn)場離奇詭異,居然都是意外死亡戈抄,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門后专,熙熙樓的掌柜王于貴愁眉苦臉地迎上來划鸽,“玉大人,你說我怎么就攤上這事戚哎÷惴蹋” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵型凳,是天一觀的道長丈冬。 經(jīng)常有香客問我,道長甘畅,這世上最難降的妖魔是什么埂蕊? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮疏唾,結(jié)果婚禮上蓄氧,老公的妹妹穿的比我還像新娘。我一直安慰自己槐脏,他們只是感情好喉童,可當我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著顿天,像睡著了一般堂氯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上牌废,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天咽白,我揣著相機與錄音,去河邊找鬼畔规。 笑死局扶,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播三妈,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼畜埋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了畴蒲?” 一聲冷哼從身側(cè)響起悠鞍,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎模燥,沒想到半個月后咖祭,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡蔫骂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年么翰,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辽旋。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡浩嫌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出补胚,到底是詐尸還是另有隱情码耐,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布溶其,位于F島的核電站骚腥,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瓶逃。R本人自食惡果不足惜束铭,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望金闽。 院中可真熱鬧纯露,春花似錦、人聲如沸代芜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挤庇。三九已至钞速,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嫡秕,已是汗流浹背渴语。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留昆咽,地道東北人驾凶。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓牙甫,卻偏偏與公主長得像,于是被迫代替她去往敵國和親调违。 傳聞我的和親對象是個殘疾皇子窟哺,可洞房花燭夜當晚...
    茶點故事閱讀 44,871評論 2 354

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,117評論 25 707
  • Java中的String類可以被繼承么? 答:不能技肩,因為它是一個final類且轨,同樣的還有Integer,F(xiàn)loat...
    gyymz1993閱讀 3,985評論 2 104
  • 前幾天整理了Java面試題集合,今天再來整理下Android相關(guān)的面試題集合.如果你希望能得到最新的消息,可以關(guān)注...
    Boyko閱讀 3,632評論 8 135
  • 幸福實修
    07何柳亞閱讀 136評論 0 0
  • 首先虚婿,我們來看一個常見的例子 我們打開控制臺旋奢,會看到首先輸出的是undefined,然后過了一秒鐘輸出’開始搖‘然痊,...
    hhg121閱讀 653評論 0 0