編輯:關於 Android 程式設計
版本:1.0 日期:2014.6.11(2014.6.12 修訂) 版權:© 2014 kince(轉載請註明出處)
ImageView 是開發中經常使用、幾乎不可或缺的控件。使用它時,除了要理解並正確設定 ScaleType 之外,還有一些值得注意的問題,例如設定大尺寸背景圖時的記憶體佔用與釋放,以及在擴展方面的應用,像圓角圖片、圓形圖片、圖片邊框等等。因此,若想熟練運用這個控件,就需要對它的實作機制有個基本了解。
ImageView 同樣是直接繼承自 View 類別,主要結構如下圖:

基於篇幅考量,這裡不貼出 ImageView 的完整程式碼,而是挑選結構圖中的重點來說明。首先是構造方法:
public ImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initImageView(); TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ImageView, defStyle, 0); Drawable d = a.getDrawable(com.android.internal.R.styleable.ImageView_src); if (d != null) { setImageDrawable(d); } mBaselineAlignBottom = a.getBoolean( com.android.internal.R.styleable.ImageView_baselineAlignBottom, false); mBaseline = a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_baseline, -1); setAdjustViewBounds( a.getBoolean(com.android.internal.R.styleable.ImageView_adjustViewBounds, false)); setMaxWidth(a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_maxWidth, Integer.MAX_VALUE)); setMaxHeight(a.getDimensionPixelSize( com.android.internal.R.styleable.ImageView_maxHeight, Integer.MAX_VALUE)); int index = a.getInt(com.android.internal.R.styleable.ImageView_scaleType, -1); if (index >= 0) { setScaleType(sScaleTypeArray[index]); } int tint = a.getInt(com.android.internal.R.styleable.ImageView_tint, 0); if (tint != 0) { setColorFilter(tint); } int alpha = a.getInt(com.android.internal.R.styleable.ImageView_drawableAlpha, 255); if (alpha != 255) { setAlpha(alpha); } mCropToPadding = a.getBoolean( com.android.internal.R.styleable.ImageView_cropToPadding, false); a.recycle(); //need inflate syntax/reader for matrix } private void initImageView() { mMatrix = new Matrix(); mScaleType = ScaleType.FIT_CENTER; mAdjustViewBoundsCompat = mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1; }可以看到,構造方法中很常規地從 attrs 讀取屬性值並加以設定。由此可見,ImageView 預設使用的 ScaleType 是 FIT_CENTER。
說到 ScaleType,它是一個列舉類型,平常使用的各種縮放模式都在這裡定義:
/** * Options for scaling the bounds of an image to the bounds of this view. */ public enum ScaleType { MATRIX (0), FIT_XY (1), FIT_START (2), FIT_CENTER (3), FIT_END (4), CENTER (5), CENTER_CROP (6), CENTER_INSIDE (7); ScaleType(int ni) { nativeInt = ni; } final int nativeInt; }它的功能是設定圖片的顯示位置與大小等方面。
接著是 onMeasure() 方法,用於計算 ImageView 的大小。如果在 XML 中指定了固定的寬高,那麼測量出來的大小就是該固定值;如果是「包裹內容(wrap_content)」,則需要進一步計算:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { resolveUri();//獲取圖片Drawable int w; int h; // ...(省略部分程式碼) setMeasuredDimension(widthSize, heightSize); }
在 onMeasure 方法中,首先呼叫 resolveUri(),目的就是為了確定 Drawable。如果設定了 drawableResource,Drawable 就是其值;否則就從 ContentResolver 取得一個 Drawable:
private void resolveUri() { if (mDrawable != null) { return; } Resources rsrc = getResources(); if (rsrc == null) { return; } Drawable d = null; if (mResource != 0) { try { d = rsrc.getDrawable(mResource); } catch (Exception e) { Log.w("ImageView", "Unable to find resource: " + mResource, e); mUri = null; } } // ...(省略其他分支) updateDrawable(d); }
resolveUri() 的最後呼叫了 updateDrawable(d),其程式碼如下:
private void updateDrawable(Drawable d) { if (mDrawable != null) { mDrawable.setCallback(null); unscheduleDrawable(mDrawable); } mDrawable = d; if (d != null) { d.setCallback(this); if (d.isStateful()) { d.setState(getDrawableState()); } d.setLevel(mLevel); d.setLayoutDirection(getLayoutDirection()); d.setVisible(getVisibility() == VISIBLE, true); mDrawableWidth = d.getIntrinsicWidth(); mDrawableHeight = d.getIntrinsicHeight(); applyColorMod(); configureBounds(); } else { mDrawableWidth = mDrawableHeight = -1; } }可見它就是為 Drawable 的寬高賦值的地方。
其中 mAdjustViewBounds 這個變量,是在 setAdjustViewBounds 方法中設定的,預設為 false,必須設為 true,onMeasure 中對應的判斷才會執行;它也可以在 XML 中透過 android:adjustViewBounds 設定。若想「固定圖片大小、同時保持寬高比」,需要如下設定:
1)將 setAdjustViewBounds 設為 true;
2)設定 maxWidth、maxHeight;
3)將 layout_width 與 layout_height 設為 wrap_content。
最後看 onDraw() 方法:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDrawable == null) { return; } if (mDrawableWidth == 0 || mDrawableHeight == 0) { return; } if (mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0) { mDrawable.draw(canvas); } else { int saveCount = canvas.getSaveCount(); canvas.save(); if (mCropToPadding) { final int scrollX = mScrollX; final int scrollY = mScrollY; canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + mRight - mLeft - mPaddingRight, scrollY + mBottom - mTop - mPaddingBottom); } canvas.translate(mPaddingLeft, mPaddingTop); if (mDrawMatrix != null) { canvas.concat(mDrawMatrix); } mDrawable.draw(canvas); canvas.restoreToCount(saveCount); } }
在 onDraw 中,若 mDrawMatrix 為空,就直接繪製圖片;若不為空,則還需繪製矩陣。這個 mDrawMatrix 是在 configureBounds() 方法中依據 ScaleType 設定的——不同的 ScaleType 會生成不同的矩陣,透過矩陣對圖像進行變換,從而呈現不同的顯示效果。
除了上述機制,另一個常用面向是「如何設定圖片資源」,有以下幾個方法:setImageResource(int resId)、setImageURI(Uri uri)、setImageDrawable(Drawable drawable)、setImageBitmap(Bitmap bm) 等,也可以在 XML 中設定。但直接使用有一個隱形弊端:若顯示的圖片過多、或單張圖片像素過大,就容易出現 OOM(記憶體溢出)。因此應依需求對圖片進行預處理,常用方法如下:
1、縮放與邊界壓縮——在記憶體中加載圖片時直接做處理:
InputStream is = this.getResources().openRawResource(R.drawable.xx); BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 10; //width,hight設為原來的十分一 Bitmap btp =BitmapFactory.decodeStream(is,null,options);
2、直接呼叫 JNI——當使用 setBackgroundResource、setImageResource 或 BitmapFactory.decodeResource 設定大圖時,這些函數在 decode 後最終都透過 Java 層的 createBitmap 完成,會消耗更多記憶體。改用 BitmapFactory.decodeStream 先建立 bitmap,再設為 ImageView 的來源,其關鍵在於直接呼叫 JNI 的 nativeDecodeAsset() 完成 decode,省去 Java 層的 createBitmap,從而節省記憶體。若在讀取時加上 Config 參數,還能進一步降低加載記憶體:
public static Bitmap readBitMap(Context context, int resId){ BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is,null,opt); }需特別注意:decodeStream 是直接讀取圖片的位元組碼,不會依機器解析度自動適應,因此需要在 hdpi、mdpi、ldpi 中分別配置對應的圖片資源,否則在不同解析度的機器上顯示大小會不一致。
3、手動回收佔用資源——雖然虛擬機會自動回收垃圾資源,但有時不夠即時,這時可手動回收:
if(!bmp.isRecycle() ){ bmp.recycle() //回收圖片所占的內存 system.gc() //提醒系統及時回收 }
4、優化 Dalvik 虛擬機的堆記憶體分配——使用 dalvik.system.VMRuntime 提供的 setTargetHeapUtilization 方法,可增強程式堆記憶體的處理效率:
private final static float TARGET_HEAP_UTILIZATION = 0.75f;在程式 onCreate 時呼叫:
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);即可。此外,也可強制定義軟體的最小堆記憶體大小:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ; VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //設置最小heap內存為6MB大小。
最後談談如何自訂一個繼承自 ImageView 的類別。以 CircleButton 為例,這是 GitHub 上一個開源專案,用來實現「帶點擊效果的圓形按鈕」:

它的實作思路是:先畫兩個圓形圖案——一個實心圓、一個圓環,圓環半徑小於實心圓半徑,因此預設看不到圓環;接著畫上設定好的圖片,覆蓋在兩者之上;最後在按下的時候啟動一個屬性動畫,將圓環放大顯示。關於更詳細的解析,可參考 android-circlebutton 的相關介紹文章。
SQLite 在 Android 中的基本用法整理
一、基本操作 1. 繼承 SQLiteOpenHelper public class UserSqliteOpenHelper extends SQLiteOpenHel
Android 官方文件導讀:Location and Sensors APIs(中)
本文接續介紹 Android 裝置中的各類感測器(Sensor),包含感測器概述、分類、框架,以及如何在程式中監聽感測器事件。感測器概述(Sensors Overview
華為榮耀5x和5c哪個好?榮耀5X與5C對比評測
榮耀暢玩5X與5C對比 榮耀暢玩5X上市較早,口碑不錯;榮耀暢玩5C則是後續推出的中低價位機型。兩者在屏幕尺寸、處理器與續航上有所不同。 榮耀暢玩5C 5C採用金屬機身
登陸界面細節實戰:自定義可一鍵清除的 EditText 與抖動動畫
登陸框的體驗往往藏在細節裡:有內容時自動出現一鍵清空按鈕,密碼填錯時輸入框抖動提示。本文用一個自定義 ClearEditText 把這兩個效果一次實現。 效果預覽