View地繪製流程
自定義繪製流程
我們都是知道Androdi的視圖數在創建時回掉用視圖的measure、layout、draw三個函數,分別對應尺寸測量、視圖佈局、繪製內容。但是,對於非ViewGroup類型來說,layout這個步驟不需要的,因爲它並不是一個視圖容器。它需要做的工作只是測量尺寸與繪製自身內容,上述SimpleImageview就是這樣的例子。
但是,SImpleImageView的尺寸測量只能根據圖片的大小進行設置,如果用戶像支持需要根據用戶設置的寬高模式來計算SimpleImageview的尺寸,而不是一概地使用圖片地寬高值作爲視圖地寬高。
在視圖樹渲染時View系統地繪製流程會從ViewRoot地performTraversals()方法中開始,在其內部調用View的measure()方法。measure()方法接收兩個參數:widthMeasureSpec和MesaureSpec的值由specSize和specMode共同組成,其中specSize記錄的時大小,specMode記錄的時規格。在支持match_parent、具體的寬高值之前,我們需要了解specMode的3種類型,如表2-1所示。
模式類型 | 說明 |
---|---|
EXACTLY | 表示父視圖希望子視圖的大小應該由specSize的值來決定的,系統默認會按照這個規則來設置子視圖的大小,開發人員當然也可以按照自己的意願設置成任意的大小,match_parent、具體的數值(如:100dp)對用的都是這個模式 |
AT_MOST | 表示子視圖最多隻能是specSize中指定的大小,開發人員你應該儘可能小地去設置這個 視圖,並且保證不會超過specSize。系統默認會按照這個規則來設置子視圖地帶線啊哦,開發人員當然也可以按照自己地意願設置成任意地大小、一般來說wrap_content對應這種模式 |
UNSPECIFIED | 表示開發人員可以將視圖按照自己地以驗設置成任意地大小,沒有任何限制。這種情況比較少見,不太會用到。 |
MeasureSpec時View種地內部類,基本都是二進制計算。由於int時32位地,用高兩位表示mode,低30位表示size,MODE_SHIFT=30地作用時移位
UNSPECIFIED:不對view大小做限制,系統使用
EXACTLY:確切地大小,如:100dp
AT_MOST:大小不可超過某數值,如:match_parent,最大不能超過你爸爸
那麼這兩個MeasureSpec又是從哪裏來的呢?其實這是從整個視圖樹控制類ViewRootImpl創建地,在ViewRootImpl地measuireHierarchy函數中會調用如下代碼獲取MeasureSpec:
if (!goodMeasure) {
childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
windowSizeMayChange = true;
}
}
從傷處程序中看到,這裏調用了getRootMesaureSpec()方法來獲取widthMesasureSpec和heightMeasureSpec的值。注意,方法種傳入的參數,參數爲窗口的寬度或者高度,而lp.width和lp.height在創建ViewGroup實例時就被賦值了,它們都等於MATCH_PARENT。然後再看一下gerRootMeasureSpec()方法的代碼,如下顯示:
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
從上述程序中可以看到,這裏使用了MeasureSpec.makeMeasureSpec.makeMeasureSpec()方法裝一個MeasureSpec,當rootDimension參數等於MATCH_PARENT時,MeasureSpec的specMode就等於EXACTLY,當rootDimension等於WRAP_CONTENT時,MeasureSpec的specMode就等於AT_MOST;並且MATCH_PARENT和WRAP_CONTENT的specSize等於windowSize的,也就以爲只根視圖總會充滿全屏的。
當構建完根視圖的MeasureSpec之後就會執行performMeasure函數從根視圖開始一層一側測量視圖的大小。最終會調用每個View的onMeasure函數,再該函數種用戶根據MeasureSpec測量View的大小,最終調用setMeasuredDimension函數設置該視圖的大小。下面我們看看SimpleImageview根據MeasureSpec設置大小的實現,修改變得部分只有測量視圖的部分,代碼如下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//獲取寬度的模式與大小
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
//高度的模式與大小
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
//設置View的寬高
setMeasuredDimension(measureWidth(widthMode, width), measureHeight(heightMode, height));
}
private int measureWidth(int mode, int width) {
switch (mode) {
case MeasureSpec.UNSPECIFIED:
case MeasureSpec.AT_MOST:
break;
case MeasureSpec.EXACTLY:
mWidth = width;
break;
}
return mWidth;
}
private int measureHeight(int mode, int height) {
switch (mode) {
case MeasureSpec.UNSPECIFIED:
case MeasureSpec.AT_MOST:
break;
case MeasureSpec.EXACTLY:
mHeight = height;
break;
}
return mHeight;
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
if (mBitmap == null) {
mBitmap = Bitmap.createScaledBitmap(bitmap, getMeasuredWidth(), getMeasuredHeight(), true);
}
//繪製圖片
canvas.drawBitmap(mBitmap, getLeft(), getTop(), mBitmapPaint);
}
在onMeasure函數種我們獲取寬高的模式與大小,然後分別調用measureWidth、measureHeigh函數根據MeasureSpec的mode與大小計算View的具體大小。在MeasureSpec.UNSPECIFIED與MeasureSpec,AT_MOST類型種,我們都將View的寬高設置爲圖片的寬高,而用戶制定了具體的大小或match_parent時,它的模式則爲EXACTLY,它的值就是MeasureSpec中的值。最後在繪製圖片時,會根據View的大小重新創建於給圖片,得到一個與View大小一致的Bitmap,然後會知道View上。
圖分別爲寬高設置爲wrap_content、match_parnt、具體值的顯示效果。
View的測量時自定義View中最爲重要的一步,如果不能正確地測量視圖地大小,那麼將會導致視圖顯示不完整等情況,這將嚴重影響View地顯示效果。因此,理解MeasureSpec以及正確地測量方法對於開發人員來說時必不可少的。
MesureSpec
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/** @hide */
@IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
@Retention(RetentionPolicy.SOURCE)
public @interface MeasureSpecMode {}
/**
* Measure specification mode: The parent has not imposed any constraint
* on the child. It can be whatever size it wants.
*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* Measure specification mode: The parent has determined an exact size
* for the child. The child is going to be given those bounds regardless
* of how big it wants to be.
*/
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* Measure specification mode: The child can be as large as it wants up
* to the specified size.
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
/**
* Creates a measure specification based on the supplied size and mode.
*
* The mode must always be one of the following:
* <ul>
* <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
* <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
* <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
* </ul>
*
* <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
* implementation was such that the order of arguments did not matter
* and overflow in either value could impact the resulting MeasureSpec.
* {@link android.widget.RelativeLayout} was affected by this bug.
* Apps targeting API levels greater than 17 will get the fixed, more strict
* behavior.</p>
*
* @param size the size of the measure specification
* @param mode the mode of the measure specification
* @return the measure specification based on size and mode
*/
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
/**
* Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
* will automatically get a size of 0. Older apps expect this.
*
* @hide internal use only for compatibility with system widgets and older apps
*/
@UnsupportedAppUsage
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
/**
* Extracts the mode from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the mode from
* @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
* {@link android.view.View.MeasureSpec#AT_MOST} or
* {@link android.view.View.MeasureSpec#EXACTLY}
*/
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
/**
* Extracts the size from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the size from
* @return the size in pixels defined in the supplied measure specification
*/
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
static int adjust(int measureSpec, int delta) {
final int mode = getMode(measureSpec);
int size = getSize(measureSpec);
if (mode == UNSPECIFIED) {
// No need to adjust size for UNSPECIFIED mode.
return makeMeasureSpec(size, UNSPECIFIED);
}
size += delta;
if (size < 0) {
Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
") spec: " + toString(measureSpec) + " delta: " + delta);
size = 0;
}
return makeMeasureSpec(size, mode);
}
/**
* Returns a String representation of the specified measure
* specification.
*
* @param measureSpec the measure specification to convert to a String
* @return a String with the following format: "MeasureSpec: MODE SIZE"
*/
public static String toString(int measureSpec) {
int mode = getMode(measureSpec);
int size = getSize(measureSpec);
StringBuilder sb = new StringBuilder("MeasureSpec: ");
if (mode == UNSPECIFIED)
sb.append("UNSPECIFIED ");
else if (mode == EXACTLY)
sb.append("EXACTLY ");
else if (mode == AT_MOST)
sb.append("AT_MOST ");
else
sb.append(mode).append(" ");
sb.append(size);
return sb.toString();
}