Android View的绘制简单分析一

以下均由源码改的不完全代码,本篇文章的目的是分析View的绘制流程,忽略计算细节,具体计算代码分析会在下篇。
ViewRootImpl中的performTraversals,有3个函数performMeasureperformLayoutperformDraw
View的绘制流程是测量,布局和绘制,现实生活中画画的话,比如说你要画一片叶子。首先你需要一张纸,纸就类似于ViewGroup,当纸的大小是确定的情况下,接下来需要确定要叶子的大小,然后确定叶子在纸中的位置也就是布局情况,最后才能绘制图像,这里我先以measure为切入点去分析。
建议,分析源码之前先了解设计模式:组合模式,模板方法模式。
这里需对组合模式有一定的了解才能理解ViewViewGroup之间的关系,并且能更好地理解Viewgroup遍历。
需要对模板方法模式有一定的了解才能理解onMeasure方法的使用,onMeasure的使用本质是钩子方法的使用。钩子方法的引入使得子类可以控制父类的行为。

先来定义ViewRootImplViewViewGroup

//ViewRootImpl.java
public class ViewRootImpl {
    private static final String TAG = "ViewRootImpl";

    boolean mFullRedrawNeeded;

    private int mWidth = -1;
    private int mHeight = -1;
    private View mView;
    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();

    public void setView(View view) {
        if (mView == null) {
            mView = view;
        }
    }

    void doTraversal() {
        performTraversals();
    }

    private void performTraversals() {
        WindowManager.LayoutParams lp = mWindowAttributes;


        performMeasure(1, 1);

        performLayout(lp, mWidth, mHeight);

        performDraw();
    }



   private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }


     private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
                               int desiredWindowHeight) {
        final View host = mView;
        if (host == null) {
            return;
        }
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());

    }

    private void performDraw() {
        final boolean fullRedrawNeeded = mFullRedrawNeeded;
        draw(fullRedrawNeeded);
    }

    private void draw(boolean fullRedrawNeeded) {

    }

}
//View.java
public class View {
    private static final String TAG = "View";
    private Context mContext;
    private Drawable mBackground;
    private int mMinWidth;
    private int mMinHeight;

    int mMeasuredWidth;
    int mMeasuredHeight;
    public static final int MEASURED_SIZE_MASK = 0x00ffffff;


    public View(Context context){
        mContext = context;
    }

    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(1,1);
    }

    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
    }

    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;
        Log.d(TAG," mMeasuredWidth = " + mMeasuredWidth + " , mMeasuredHeight = " + mMeasuredHeight);
    }


    public void layout(int l, int t, int r, int b) {

    }



    public final int getMeasuredWidth() {
        return mMeasuredWidth & MEASURED_SIZE_MASK;
    }

    public final int getMeasuredHeight() {
        return mMeasuredHeight & MEASURED_SIZE_MASK;
    }



    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

    protected int getSuggestedMinimumHeight() {
        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
    }

}
public abstract class ViewGroup extends View {
    private static final String TAG = "View";

    // Child views of this ViewGroup
    private View[] mChildren;

    private int mChildrenCount;
    private static final int ARRAY_INITIAL_CAPACITY = 12;
    private static final int ARRAY_CAPACITY_INCREMENT = 12;
    private int mLastTouchDownIndex = -1;

    public ViewGroup(Context context) {
        super(context);

        mChildren = new View[ARRAY_INITIAL_CAPACITY];
        mChildrenCount = 0;
    }

    public int getChildCount() {
        return mChildrenCount;
    }


    public View getChildAt(int index) {
        if (index < 0 || index >= mChildrenCount) {
            return null;
        }
        return mChildren[index];
    }

    public void addView(View child, int index) {
        addViewInner(child, index);
    }

    private void addViewInner(View child, int index) {
        addInArray(child, index);
    }

    private void addInArray(View child, int index) {
        View[] children = mChildren;
        final int count = mChildrenCount;
        final int size = children.length;
        if (index == count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, size);
                children = mChildren;
            }
            children[mChildrenCount++] = child;
        } else if (index < count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, index);
                System.arraycopy(children, index, mChildren, index + 1, count - index);
                children = mChildren;
            } else {
                System.arraycopy(children, index, children, index + 1, count - index);
            }
            children[index] = child;
            mChildrenCount++;
            if (mLastTouchDownIndex >= index) {
                mLastTouchDownIndex++;
            }
        } else {
            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
        }
    }

}

由于ViewGroup是抽象类,不能直接作为根节点使用,所以新建一个类继承ViewGroup,这里命名为FrameLayout。这里重写了onMeasure

public class FrameLayout extends ViewGroup{

    public FrameLayout(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            //measure(1, 1)是随便赋值的。
            // 通过调用child.measure去遍历ViewGroup下的所有节点的大小
            child.measure(1, 1);
        }
    }

}

下面再构建两个View节点。这里可以命名为TextViewImageView

public class TextView extends View {
    private static final String TAG = "TextView";

    public TextView(Context context){
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;
        //这中间略过了根据widthMeasureSpec和heightMeasureSpec等参数计算width, height的过程
        // 就当计算出的结果为10,因为本文目的是梳理大致流程
        width = 10;
        height = 10;
        //计算出实际的width, height然后存储
        setMeasuredDimension(width, height);
    }
    
}
public class ImageView extends View {
    private static final String TAG = "ImageView";

    public ImageView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;
        //略过了根据widthMeasureSpec和heightMeasureSpec等参数计算width, height的过程
        width = 20;
        height = 20;
        //计算出实际的width, height然后存储
        setMeasuredDimension(width, height);
    }
}

调用如下。先把TextViewImageView添加到FrameLayout中,然后通过调用setView传递到ViewRoot中,然后调用doTraversal,再走到performMeasure,最后mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);。这个mView就是mFrameLayout。由于FrameLayout中重写了onMeasure,所以执行mFrameLayout.measure会遍历测量子View的大小。

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private ViewRootImpl mViewRoot;
    private FrameLayout mFrameLayout;
    private TextView mTextView;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFrameLayout = new FrameLayout(this);
        mImageView = new ImageView(this);
        mTextView = new TextView(this);

        mFrameLayout.addView(mTextView,0);
        mFrameLayout.addView(mImageView,1);
        mViewRoot = new ViewRootImpl();
        mViewRoot.setView(mFrameLayout);
        mViewRoot.doTraversal();

    }

}

运行后Log如下。

View:  mMeasuredWidth = 10 , mMeasuredHeight = 10
D/View:  mMeasuredWidth = 20 , mMeasuredHeight = 20

ViewRootImplView是聚合关系。
ViewViewGroup是依赖 + 自关联。

关系图如下:


这里ViewViewGroup首先是用到了设计模式中的组合模式,组合模式是一种结构型模式,用来处理树形结构。
设计模式的艺术软件开发人员内功修炼之道

整体流程如果再加上performLayoutperformDraw,那么调用流程就基本上是下面的图。但是performTraversalsperformMeasureperformLayout以及performDraw不属于ViewGroup,应该加到ViewRootImpl里面去。也可以想象成把上面的图中的Measure文字换成Layout

https://www.jianshu.com/p/aa3b1f9717b7

实际上是这样的

参考链接:
View的绘制流程(三):ViewRootImpl.performTraversals()方法
performTraversals()分析
Android视图框架Activity,Window,View,ViewRootImpl理解
Android 源码分析 - View的measure、layout、draw三大流程
浅析Android View的Measure过程
Android自定义控件系列七:详解onMeasure()方法中如何测量一个控件尺寸(一)
从数据结构与算法以及设计模式角度去学习View的绘制流程
Android 之 ViewTreeObserver 全面解析
从Android源码分析View绘制流程
通过抽象的方式来讲一讲View的绘制流程
源码分析篇 - Android绘制流程(二)measure、layout、draw流程
深入理解MeasureSpec
addView方法分析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269