《Android自定义控件入门到精通》文章索引 ☞ https://blog.csdn.net/Jhone_csdn/article/details/118146683
《Android自定义控件入门到精通》所有源码 ☞ https://gitee.com/zengjiangwen/Code
文章目录
Text
drawText(String text, float x, float y, Paint paint)
不知道大家有没有这样的经历,在绘制文字的时候,总是把握不住绘制的精确位置,比如,我想在矩形中,居中绘制"Android"
@Override
protected void onDraw(Canvas canvas) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(2);
mPaint.setTextSize(14);
mPaint.setColor(Color.YELLOW);
Rect rect = new Rect(10, 10, 120, 60);
canvas.drawRect(rect, mPaint);
//获取文字宽度
float textWidth = mPaint.measureText("Android");
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
//获取文字高度
float textHeight=fontMetrics.bottom-fontMetrics.top;
float x= rect.left+(rect.width()-textWidth)/2;
float y=rect.top+(rect.height()-textHeight)/2;
canvas.drawText("Android",x,y,mPaint);
}
我们预测drawText()中的x、y为开始绘制的坐标,即猜测以上代码可以实现文字水平垂直居中,但现实往往会打脸:
水平是居中了,但这个垂直居中有点让人摸不着头脑啊!
在前几篇中,我们绘制各种图形,都是以左上角为起始点开始绘制,为啥到了文字绘制这,不灵了呢?
还记得小学时候抄过的字母吗?
本子上每行的四条线,特别是红线是不是记忆尤新?
同样的,Android中Text的绘制也有对应的四条线
@Override
protected void onDraw(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(1);
mPaint.setColor(Color.YELLOW);
mPaint.setTextSize(48);//设置文字大小为12像素
String text = "abcdefghijklmnopqrst";
float textWidth = mPaint.measureText(text);
int x = 100, y = 100;
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
float top = fontMetrics.top;
float ascent = fontMetrics.ascent;
float descent = fontMetrics.descent;
float bottom = fontMetrics.bottom;
mPaint.setColor(Color.YELLOW);
canvas.drawLine(x, top + y, x + textWidth, top + y, mPaint);
mPaint.setColor(Color.RED);
canvas.drawLine(x, ascent + y, x + textWidth, ascent + y, mPaint)