Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> View的繪制原理

View的繪制原理

編輯:關於Android編程

1.初識ViewRoot和DecorView

ViewRoot對應於ViewRootImpl類,它是連接WindowManager和DecorView的紐帶,View的三大流程均是通過ViewRoot來完成的,在ActivityThread中,當ActivityThread中,當Activity對象被創建完畢後,會將DecorView添加到Window中,同時會創建ViewRootImpl對象,並將ViewRootImpl對象和DecorView建立關聯。

View的繪制過程就是從ViewRoot的performTraversals方法開始的,它經過measure、layout、draw三個過程才能最終將一個View繪制出來:
1.measure用來測量View的寬和高。
2.layout用來確定View在父容器中放置的位置。
3.draw用來將view繪制在屏幕上。

大致的流程如下圖所示:
這裡寫圖片描述

如圖所示,performTraversals會依次調用performMeasure、perfZ喎?/kf/ware/vc/" target="_blank" class="keylink">vcm1MYXlvdXS6zXBlcmZvcm1EcmF3yP249re9t6ijrNXiyP249re9t6i31rHwzeqzybalvLZWaWV3tcRtZWFzdXJloaJsYXlvdXShomRyYXfV4rj2yP249sH3s8yho8bk1tCjujwvcD4NCjxwPjEucGVyZnJvbU1lYXN1cmXW0LvhtffTw21lYXN1cmW3vbeoo6zU2m1lYXN1cmW3vbeo1tDT1rvhtffTw29uTWVhc3VyZbe9t6ijrNTab25NZWFzdXJlt723qNbQu+G21Mv509C1xNfT1KrL2L340NBtZWFzdXJluf2zzKOs1eK49sqxuvJtZWFzdXJlwfezzL7NtNO4uMjdxve0q7Xdtb3X09Sqy9jW0MHLo6zV4tH5vs3N6rPJwcvSu7TObWVhc3VyZbn9s8yho73T18XX09Sqy9i74dbYuLS4uNSqy9i1xG1lYXN1cmW5/bPMo6zI57TLt7S4tL7NzeqzydX7uPZWaWV3yve1xLHpwPqhozwvcD4NCjxwPjIucGVyZm9ybUxheW91dLXEtKu13cH3s8y6zXBlcmZvcm1NZWFzdXJlysfSu9H5tcShozwvcD4NCjxwPjMucGVyZm9ybURyYXe1xLSrtd25/bPMysfU2mRyYXe3vbeo1tDNqLn9ZGlzcGF0aERyYXfAtMq1z9a1xKOssb7WysnPsqLDu9PQx/ix8KGjPC9wPg0KPHA+TWVhc3VyZbn9s8y+9raowctWaWV3tcS/7bjfo6xNZWFzdXJlzeqzydLUuvOjrL/J0tTNqLn9Z2V0TWVhc3VyZWRXaWR0aLrNZ2V0TWVhc3VyZWRIZWlnaHS3vbeowLS78cihtb1WaWV3suLBv7rztcS/7bjfo6zU2ry4uvXL+dPQtcTH6b/2z8LL/La8tcjT2lZpZXe1xNfu1tW/7bjfo6zV4r32vfbKx9TatPrC67nmt7a1xMewzOHWrs/CoaM8YnIgLz4NCmxheW91dNfu1tW+9raowctWaWV3tcTLxLj2tqW147XE1/ix6rrNyrW8ylZpZXe1xL/tL7jfo6zN6rPJ0tS686Osv8nS1M2ouf1nZXRUb3ChomdldEJvdHRvbaGiZ2V0TGVmdKGiZ2V0UmlnaHTAtMTDtb1WaWV3tcTLxLj2tqW149f4serOu9bDo6yyor/J0tTNqLn9Z2V0V2lkdGi6zWdldEhlaWdodMC0tcO1vVZpZXe1xNfu1tW/7bjfPC9wPg0KPHA+ZHJhd7n9s8y+9raowctWaWV3tcTP1Mq+o6zWu9PQZHJhd7e9t6jN6rPJ0tS681ZpZXe1xMTayN2yxbvh1+7W1c/Uyr7U2sbBxLvJz6GjPC9wPg0KPHA+z8LD5s7Sw8fAtMjPyrbSu8/CRGVjb3JWaWV3o6zV4rj2ysdBY3Rpdml0ebXEtqW8tlZpZXehozwvcD4NCjxwPjxpbWcgYWx0PQ=="![enter description here][2]" src="/uploadfile/Collfiles/20160729/20160729093546661.png" title="\" />

大家應該還記得我們在Activity中加載布局使用的方法吧!setContentView,那個contentview就是我們這個DecroView中的子布局,從之前的博文View的事件分發中,我們也可以了解到View的點擊事件都要先經過DecorView,然後再傳遞給我們的View。

1.2 理解MeasureSpec

MeasureSpec的中文意思是測量規格的意思,MeasureSpec代表一個32的int值,高2位代表SpecMode測量模式,低30位代表SpecSize測量規格大小。

經常使用的三個函數:
1.public static int makeMeasureSpec(int size,int mode)
構造一個MeasureSpec

2.public static int getMode(int measureSpec)
獲取MeasureSpec的測量模式

3.public static int getSize(int measureSpec)
獲取MeasureSpec的測量大小

SpecMode分為三類,每一類都沒有他們對應的約束。

1.UNSPECIFIED
父容器不對View有任何限制,要多大就給多大,這種情況,一般我們自定義View用不到。

2.Exactly
這個表示准確值,這個對應著LayoutParams中的matchparent和准確值,這個時候View的最終大小就是SpecSize所指定的數。

3.AT_MOST
父容器指定了一個可用大小即SpecSize,View的大小不能大於該值,具體是什麼要看View中自己的處理,所有自定義View時,我們需要自己在measure裡面處理設置布局的大小,它對應layoutparams中的wrap_content

2.1 MeasureSpec和LayoutParams的關系

在上面系統中,使用MeasureSpec來進行View的測量,但是正常情況下我們使用View指定MeasureSpec,盡管如此,但是我們可以給View設置layoutparams,在View測量的時候,系統會將LayoutParams在父容器的約束下自動轉化成對應的MeasureSpec,然後再根據MeasureSpec來確定View最終的寬高。

MeasureSpec不是由LayoutParams唯一決定的,子View的寬高由自身的layoutparams和父容器的MeasureSpec。

對於DecorView,其MeasureSpec由窗口的尺寸和自身的Layoutparams決定;
對於普通的View,其MeasureSpec由父容器的MeasureSpec和自身的Layoutparams共同決定;

遵循的規則:
1.LayoutParams.MATCH_PARENT:精確模式,大小就是窗口的大小
2.LayoutParams.WRAP_CONTENT:最大模式,大小不定,但是不能超過窗口的大小
3.固定大小(比如100dp):精確模式,大小為LayoutParams中指定的大小
**4.當view采用固定的寬高時,不管父容器的MeasureSpec是什麼,View的MeasureSpec都是精確模式並且大小遵循LayoutParams的大小
5.當View的寬高時matchparent時,如果父容器是精確模式,那麼View也是精確模式,並且View也是精確模式並且大小是父容器的剩余空間。如果父容器是最大模式,那麼View也是最大模式但是大小不能超過剩余的空間。
6.當View是wrap_content,那麼不管父容器的模式,View一定是最大模式,但是不能超過父容器的剩余空間。**
\

3. View的工作流程

View的工作流程主要是指measure、layout、draw這三個流程,即測量、布局、繪制,其中measure確定View的測量寬高,layout確定View的最終寬高和上下左右的位置,draw將View繪制到屏幕上。

3.1 measure操作

measure過程要分情況來看:
1.針對View的measure過程
View的measure過程由其meaure方法完成,measure方法是一個final類型的方法,子類不可以重寫此方法,因為View的measure內部會調用onMeasure方法,我們來看一下View的onMeasure的實現即可。

    @CallSuper
    public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * 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)
         */

        // Step 1, draw the background, if needed
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // we're done...
            return;
        }

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

        // Overlay is part of the content and draws beneath Foreground
        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }

        // Step 6, draw decorations (foreground, scrollbars)
        onDrawForeground(canvas);
    }

View的繪制過程的傳遞是通過dispatchDraw實現的,dispatchdraw會遍歷調用所有子元素的draw方法。如此draw事件就一層一層的傳遞下去。

好,大結局。學習好上面的所有知識,我們就要打開自定義View的大門了啊,Follow Me!!!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved