Android BitmapDrawable()的使用,bitmapdrawable

來源:互聯網
上載者:User

Android BitmapDrawable()的使用,bitmapdrawable

查看源碼BitmapDrawable.java。BitmapDrawable有若干個構造方法。

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),不同的是前者傳入一個Resources的NULL值,後者傳入了一個非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確定一個正確的密度(S4為480)。否則會採用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);

 

總結,因為兩個構造方法參數不同,得到兩個不同的寬高值,於是在繪製中就出現介面異常。(具體為什麼算出來的Width和height差異很大還需要繼續調查,有興趣的可以再查查)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.