1. 程式人生 > >趙雅智_setImageResource和setImageBitmap

趙雅智_setImageResource和setImageBitmap

在4.0.4 r1.2中檢視android.widget.ImageView原始碼可以發現,setImageBitmap()方法其實是呼叫了setImageDrawable()方法進行重繪。

Sets a Bitmap as the content of this ImageView.  
  
Parameters:  
bm The bitmap to set  
  
@android.view.RemotableViewMethod  
public void setImageBitmap(Bitmap bm) {  
    // if this is used frequently, may handle bitmaps explicitly  
    // to reduce the intermediate drawable object  
    setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));  
}  


Sets a drawable as the content of this ImageView.  
  
Parameters:  
drawable The drawable to set  
  
public void setImageDrawable(Drawable drawable) {  
    if (mDrawable != drawable) {  
        mResource = 0;  
        mUri = null;  
  
        int oldWidth = mDrawableWidth;  
        int oldHeight = mDrawableHeight;  
  
        updateDrawable(drawable);  
  
        if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeigh{  
            requestLayout();  
        }  
        invalidate();  
    }  
}  

同樣的佈局檔案,小解析度手機:

1、使用setImageBitmap設定時,出現如下現象:


 2、使用setImageResource時,圖片顯示正常


 原因:

setImageResource(id)會根據裝置解析度進行圖片大小縮放適配

setImageBitmap(BitmapFactory.decodeResource(res,id))大小需要手動調。

如果你提供了完整的各種解析度下的圖片的話,兩種方法都應該不會有混亂。