Android里面的textview是一个相当重要的类。相信做安卓的开发人员在每一个应用里面都一定用到了它,而且它也是Button,EditTextView等子控件的父类。
对于View的流程:measure ->layout -> draw ; measure会调用子类的onMeasure,同理layout调用子类的onLayout,draw会调用子类的onDraw(drawCanvas临时不讨论)。
先把大致流程理出来,然后我们去源代码里面找相应的函数(android-23里面相应的源代码)。
首先看下onMeasure()
方法里面干了什么事情
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//以上省略代码...
// 推断文字绘制的方向
if (mTextDir == null) {
mTextDir = getTextDirectionHeuristic();
}
int des = -1;
boolean fromexisting = false;
// 測量宽度
if (widthMode == MeasureSpec.EXACTLY) {
// Parent has told us how big to be. So be it.
width = widthSize;
} else {
if (mLayout != null && mEllipsize == null) {
des = desired(mLayout);
}
// BoringLayout.isBoring推断是否是单行文本(详细实现參见BoringLayout)
if (des < 0) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
if (boring != null) {
mBoring = boring;
}
} else {
fromexisting = true;
}
//以上省略代码...
// 这里创建mLayout
if (mLayout == null) {
makeNewLayout(want, hintWant, boring, hintBoring,
width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
}
//以上省略代码...
// 设置測量好的宽高
setMeasuredDimension(width, height);
}
上面的代码主要去计算了textview显示的宽度以及构造出来了一个mLayout
,那继续看下调用makeNewLayout()
函数里面做了些什么:
/**
* The width passed in is now the desired layout width,
* not the full view width with padding.
* {@hide}
*/
protected void makeNewLayout(int wantWidth, int hintWidth,
BoringLayout.Metrics boring,
BoringLayout.Metrics hintBoring,
int ellipsisWidth, boolean bringIntoView) {
//以上省略代码...
// 这里真正产生mLayout
mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
effectiveEllipsize, effectiveEllipsize == mEllipsize);
//以上省略代码...
}
那我们进入makeSingleLayout()
的code:
private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
boolean useSaved) {
Layout result = null;
// 这里依据mText 的类型创建了3种不同的Layout
if (mText instanceof Spannable) {
result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad,
mBreakStrategy, mHyphenationFrequency,
getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth);
} else {
if (boring == UNKNOWN_BORING) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
if (boring != null) {
mBoring = boring;
}
}
//以上省略代码...
// 以下使用Builder模式创建StaticLayout
if (result == null) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
0, mTransformed.length(), mTextPaint, wantWidth)
.setAlignment(alignment)
.setTextDirection(mTextDir)
.setLineSpacing(mSpacingAdd, mSpacingMult)
.setIncludePad(mIncludePad)
.setBreakStrategy(mBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency);
if (shouldEllipsize) {
builder.setEllipsize(effectiveEllipsize)
.setEllipsizedWidth(ellipsisWidth)
.setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
}
// TODO: explore always setting maxLines
result = builder.build();
}
return result;
}
介绍下TextView的基本渲染原理,总的来说。TextView中负责渲染文字的主要是这三个类:
BoringLayout
主要负责显示单行文本。并提供了isBoring方法来推断是否满足单行文本的条件。DynamicLayout
当文本为Spannable的时候。TextView就会使用它来负责文本的显示,在内部设置了SpanWatcher。当检測到span改变的时候,会进行reflow,又一次计算布局。StaticLayout
当文本为非单行文本。且非Spannable的时候,就会使用StaticLayout,内部并不会监听span的变化,因此效率上会比 DynamicLayout高,仅仅需一次布局的创建就可以,但事实上内部也能显示SpannableString,仅仅是不能在span变化之后又一次进行布局而已。
这里引出一个有一个Spannable
是一个接口,它的实现类有SpannableString
,SpannableStringBuilder
,当我们在使用textView.setText()
的时候能够传入这2种类型的參数,举个样例比方我们须要在textview里面显示一个emoji表情:
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.hanguo);
ImageSpan imgSpan = new ImageSpan(this, b);
SpannableString spanString = new SpannableString("icon");
spanString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanString);
这里都是图片塞入SpannableString
然后利用textView.setText
。假设你须要加入多个能够用SpannableStringBuilder
。
回归主线,之前我们把onMeasure
和onLayout
2个方法大体思路看完了,如今该去看看它的onDraw
里面做了一些哪些魔法的事情。
@Override
protected void onDraw(Canvas canvas) {
// 绘制相应xml里面drawLeft等4个方向的图片
final int compoundPaddingLeft = getCompoundPaddingLeft();
final int compoundPaddingTop = getCompoundPaddingTop();
final int compoundPaddingRight = getCompoundPaddingRight();
final int compoundPaddingBottom = getCompoundPaddingBottom();
// 省略很多代码...
if (mEditor != null) {
mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical);
} else {
// 这里真的绘制调用了layout的draw,就是之前产生3中Layout中的当中一种
layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
}
主要做法先绘制drawLeft等4个方向的图片(假设有的话),再调用layout.draw()
去绘制文字,好的我们进入里面去看下
/**
* Draw this Layout on the specified canvas, with the highlight path drawn
* between the background and the text.
*
* @param canvas the canvas
* @param highlight the path of the highlight or cursor; can be null
* @param highlightPaint the paint for the highlight
* @param cursorOffsetVertical the amount to temporarily translate the
* canvas while rendering the highlight
*/
public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
int cursorOffsetVertical) {
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
firstLine, lastLine);
drawText(canvas, firstLine, lastLine);
}
代码非常短。看方法命名都知道
- 先绘制背景
- 绘制文字
我们主要关心怎么绘制文字信息的。看下
public void drawText(Canvas canvas, int firstLine, int lastLine) {
// 省略他大爷的那么多代码
if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTabOrEmoji) {
// XXX: assumes there's nothing additional to be done
canvas.drawText(buf, start, end, x, lbaseline, paint);
} else {
tl.set(paint, buf, start, end, dir, directions, hasTabOrEmoji, tabStops);
tl.draw(canvas, x, ltop, lbaseline, lbottom);
}
paint.setHyphenEdit(0);
}
TextLine.recycle(tl);
}
主要看到了drawText()
,心里的石头放下来了;可是这里又有2中情况:
- 仅仅有文本信息
直接调用canvas.drawText
- 包括图片信息
使用TextLine的draw()
绘制。去TextLine的draw()里面:
void draw(Canvas c, float x, int top, int y, int bottom) {
if (!mHasTabs) {
if (mDirections == Layout.DIRS_ALL_LEFT_TO_RIGHT) {
// 这里会调用TextLine的handleRun(),里面的span.updateDrawState(wp),能够改变文字的颜色和下划线是否显示
drawRun(c, 0, mLen, false, x, top, y, bottom, false);
return;
}
// 省略代码...
if (emojiRect == null) {
emojiRect = new RectF();
}
emojiRect.set(x + h, y + bmAscent,
x + h + width, y);
// 这里调用drawBitmap绘制图片
c.drawBitmap(bm, null, emojiRect, mPaint);
h += width;
j++;
}
segstart = j + 1;
}
}
}
}