前言
自定义View
是分两种的,一种是继承自View
,一种是继承自ViewGroup
。之前我写过关于继承自ViewGroup
的博客,同时还有流式布局实战(流式布局讲解链接)。那么这一篇主要是来继承自View
的TextView
绘制。
这边为了演示方便,就继承自AppCompatTextView
。因为这样可以不用重写onMeasure
。把重心放在draw
上面,即只需要重写onDraw
。
两个东西,画布和画笔,即Canvas
和Paint
。这两个东西就不过多介绍了
OK,下面让我们走进自定义TextView
1.baseLine
我们在Canvas
的drawText
方法中,有一个参数是y
。这个y
,就是baseLine
,也就是基准线。
那么啥玩意是基准线呢?我们看这么一张图
上面有标出baseLine
在哪。通俗来讲,就是所有文字都差不多根据这根线对齐。当然并不是说完全对齐,也不是说完全不超过这根线,但是可以确定的是,所有的文字,是以它为基准的。可以把它看作针对自定义TextView
中坐标系的0
。
2.如何将TextView水平对齐
为了方便显示效果,我们先用一个方法,画出X轴的中心线
//画x轴的中心线
private void drawCenterLineX(final Canvas canvas){
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setStrokeWidth(3);
canvas.drawLine(getWidth()/2,0,getWidth()/2,getHeight(),paint);
}
方式①:更改文字对齐方式
float x = getWidth()/2;
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(mText,x,99,paint);
即设置为中间对齐。默认为左对齐,如果不设置,即没有使用setTextAlign
方法的话,会是这种情况
即采用的默认的TextView
最左边(即x
)为getWidth()/2
。如果设置的话就是TextView
的中间为getWidth()/2
,即
方式②:利用TextView宽度
float x = getWidth()/2 - paint.measureText(mText)/2;
canvas.drawText(mText,x,99,paint);
这个逻辑很简单我就不再解释了。measureText
方法为测量文字宽度,源码为
/**
* Return the width of the text.
*
* @param text The text to measure. Cannot be null.
* @return The width of the text
*/
public float measureText(String text) {
if (text == null) {
throw new IllegalArgumentException("text cannot be null");
}
return measureText(text, 0, text.length());
}
3.如何将TextView竖直对齐
首先要了解四个变量的含义:top、bottom、ascent、descent
这四个东西可以理解成四条线。先放一下源码的意思
//此类是Paint.FontMetrics,它保存着TextView的一些尺寸信息;
/**
* Class that describes the various metrics for a font at a given text size.
* Remember, Y values increase going down, so those values will be positive,
* and values that measure distances going up will be negative. This class
* is returned by getFontMetrics().
*/
public static class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
public float top;
/**
* The recommended distance above the baseline for singled spaced text.
*/
public float ascent;
/**
* The recommended distance below the baseline for singled spaced text.
*/
public float descent;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
public float bottom;
/**
* The recommended additional space to add between lines of text.
*/
public float leading;
}
ok,不太懂没关系,看下面的图