一起Talk Android吧(第一百五十四回:Android自定义View之Draw六)

mac2024-01-27  31

各位看官们大家好,上一回中咱们说的是Android中自定义View之Draw的例子,这一回咱们继续说该例子。闲话休提,言归正转。让我们一起Talk Android吧!

看官们,我们在一回中介绍了ViewGroup的Draw流程,这一回中我们将以ViewGroup的直接子类LinearLayout为例子进行说明。

我们在上一回中介绍了ViewGroup的Draw流程,该流程的末端是onDraw()函数,不过ViewGroup并没有定义该函数,而是把它离给了子类去实现,因此,我们以LinearLayout为例子来介绍onDraw()函数的过程。下面是它的源代码:

@Override protected void onDraw(Canvas canvas) { if (mDivider == null) { return; } if (mOrientation == VERTICAL) { drawDividersVertical(canvas); } else { drawDividersHorizontal(canvas); } }

从源代码中可以看到,它分水平和垂直两种情况进行绘制,我们以垂直绘制为例来说明,于是我 们先看看 drawDividersVertical()函数的源代码,具体如下:

void drawDividersVertical(Canvas canvas) { final int count = getVirtualChildCount(); for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child != null && child.getVisibility() != GONE) { if (hasDividerBeforeChildAt(i)) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int top = child.getTop() - lp.topMargin - mDividerHeight; drawHorizontalDivider(canvas, top); } } } if (hasDividerBeforeChildAt(count)) { final View child = getLastNonGoneChild(); int bottom = 0; if (child == null) { bottom = getHeight() - getPaddingBottom() - mDividerHeight; } else { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); bottom = child.getBottom() + lp.bottomMargin; } drawHorizontalDivider(canvas, bottom); } }

从源代码中可以看出,它主要是通过drawHorizontalDivider()函数实现绘制功能。于是我们再看看该函数的源代码:

void drawHorizontalDivider(Canvas canvas, int top) { mDivider.setBounds(getPaddingLeft() + mDividerPadding, top, getWidth() - getPaddingRight() - mDividerPadding, top + mDividerHeight); mDivider.draw(canvas); }

从源代码中可以看出它是通过调用Drawable对象的draw()函数实现绘制功能的。

各位看官,关于Androd中自定义View之Draw的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!

最新回复(0)