概述
View和ViewGroup是Android显示系统的一部分,上层应用画图的基础。为了方便使用,Android也提供了很多widget(ImageView TextView LinearLayout RelativeLayout等)。View和ViewGroup其实是component模式,架构图如下:
画图原理
如果让我们自己设计一个View系统,我们会提供哪些掊口呢?
可能我们首先想到画纸,画笔,颜料。然后确定要画什么物体、物体的大小
、物体的位置、物体的着色。这就是我们对绘画流程的基本认知。不错,View的显示也是这么干的。Canvas、Paint、Color、Measure、Layout 、Draw都是View的基本元素。自定义View很重要,但是我们程序员除非逼不得已,一般都不会选择通过自定义View来实现自己的UI。其实原因也很简单,给你画纸、画笔、颜料,并且你熟知绘画流程,你能画出来蒙拉丽莎吗?
自定义View给你很大的自由,理论上能实现你想要的任何UI,但是驾驭是不容易的,添加了困难和复杂度。所以不要抱怨系统提供的widget不灵活,有时它是符合单一原则,提供简单的操作。
自定义View三步骤
Measure、Layout 、Draw是自定义View最重要的三步骤,也符合我们对绘画的认知,先确定物体的大小,再确实物体的位置,然后开始绘制物体。
但对View树来说,Measure、Layout、Draw都是管理类ViewRootImpl.java调用的,View只需要重写OnMeasure、onLayout、onDraw方法实现自己的逻辑就可以了。
ViewRootImpl.java中有一个很重要的方法performTraversals,绘制从根视图,从上到下遍历整个视图树,每个View空间负责绘制自己,而ViewGroup还要负责告诉自己的子View开始进行绘制。视图树绘制可以分为三个步骤:分别是测量Measure ,布局 Layout ,绘制 Draw。三个接口如下:
- performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
- performLayout(lp, mWidth, mHeight);
- performDraw();
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
\\ 最终调用view measure,其实现会调用OnMeasure
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
......
}
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
mLayoutRequested = false;
mScrollMayChange = true;
mInLayout = true;
final View host = mView;
if (host == null) {
return;
}
if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
Log.v(mTag, "Laying out " + host + " to (" +
host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
try {
// 会调用View layout,layout 会调用onLayout方法
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
.........
}
..........
}
通过上面的代码可以看出Meassure 、Layout是怎么调用到View的onMeasure、onLayout, 比较清楚的简单。
draw流程
draw比较复杂,单独梳理,流程如下:
ViewRootImpl.java
- performDraw();
- draw(boolean fullRedrawNeeded);
ThreadedRenderer.java
- void draw(View view, AttachInfo attachInfo, ThreadedRenderer.DrawCallbacks callbacks, ThreadedRenderer.FrameDrawingCallback frameDrawingCallback);
- updateRootDisplayList(View view, DrawCallbacks callbacks);
- updateViewTreeDisplayList(View view);
View.java
- RenderNode updateDisplayListIfDirty();
- void draw(Canvas canvas);
- void onDraw(Canvas canvas);
上面就是draw调用流程,View那一层的draw其实是调用到DecorView中的draw,因为传给ThreadedRenderer.java中的View就是DecorView.DecorView会调用父类的draw,后面就会调用到View中的onDraw。
private void performDraw() {
if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
return;
} else if (mView == null) {
return;
}
final boolean fullRedrawNeeded = mFullRedrawNeeded || mReportNextDraw;
mFullRedrawNeeded = false;
mIsDrawing = true;
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
......
try {
// 调用自己的draw方法
boolean canUseAsync = draw(fullRedrawNeeded);
if (usingAsyncReport && !canUseAsync) {
mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
usingAsyncReport = false;
}
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
.....
private boolean draw(boolean fullRedrawNeeded) {
Surface surface = mSurface;
if (!surface.isValid()) {
return false;
}
if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
if (mAttachInfo.mThreadedRenderer != null && mAttachInfo.mThreadedRenderer.isEnabled()) {
// If accessibility focus moved, always invalidate the root.
boolean invalidateRoot = accessibilityFocusDirty || mInvalidateRootRequested;
mInvalidateRootRequested = false;
..........
final FrameDrawingCallback callback = mNextRtFrameCallback;
mNextRtFrameCallback = null;
// 现在版本使用的是这个方法draw的
mAttachInfo.mThreadedRenderer.draw(mView, mAttachInfo, this, callback);
........
void draw(View view, AttachInfo attachInfo, DrawCallbacks callbacks,
FrameDrawingCallback frameDrawingCallback) {
attachInfo.mIgnoreDirtyState = true;
final Choreographer choreographer = attachInfo.mViewRootImpl.mChoreographer;
choreographer.mFrameInfo.markDrawStart();
// 这个方法可以调用到updateDisplayListIfDirty(),然后调用view的draw方法
updateRootDisplayList(view, callbacks);
// 这个方法完成后,就可以上屏了
int syncResult = nSyncAndDrawFrame(mNativeProxy, frameInfo, frameInfo.length);
}
public RenderNode updateDisplayListIfDirty() {
if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
dispatchDraw(canvas);
drawAutofilledHighlight(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().draw(canvas);
}
if (debugDraw()) {
debugDrawFocus(canvas);
}
} else {
// 调用draw方法,其实是调用DecorView的draw方法
draw(canvas);
}
}
自定义View的实现接口
上面梳理了View系统的Measure、Layout、Draw流程,其实对应用开发来说,只需要重写onMeasure、onLayout、onDraw方法。
onMeasure相关的知识
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法,两个int类型的参数,并且不是宽和高。而是MeasureSpec。
MeasureSpec表示的是一个32位的整型值,他的高2位表示测量模式SpecMode,低30位表示某种测量模式下的规格大小SpecSize .
MeadureSpec 是View类的一个静态内部类,用来表示如何测量这个View 。
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 {}
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;
........
}
通过MeasureSpec计算View的宽高,然后调用setMeasuredDimension(measuredWidth, measuredHeight)这个接口设置此View的宽高。
onLayout
/**
* Called from layout when this view should
* assign a size and position to each of its children.
*
* Derived classes with children should override
* this method and call layout on each of
* their children.
* @param changed This is a new size or position for this view
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
*/
onDraw
/**
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
参数资料
https://www.jianshu.com/p/e9d8420b1b9c