天天看点

自定义View绘制文字居中显示

Paint textPaint = new Paint( Paint.ANTI_ALIAS_FLAG);    

textPaint.setColor( Color.WHITE);    

String text = "你好吗";    

// 计算textsize

int width = getMeasuredWidth(); // 获取控件的寬高

int height = getMeasuredHeight();

float textSize = width/6.0f; // 人为设定size无关紧要,重要部分在下面

textPaint.setTextSize(textSize);

// FontMetrics对象 

FontMetrics fontMetrics = textPaint.getFontMetrics();    // 获取这个对象就可以获取到文本的高度了

float textWidthTotal = textPaint.measureText(text);  // 计算整体文字的宽度

float textHeight = fontMetrics.descent-fontMetrics.ascent; // 计算文字的高度

// 计算每一个坐标 

float baseX = width/2.0f - textWidthTotal/2.0f;    // 绘制文字的起始x坐标值

float baseY = (height/2.0f - textHeight/2.0f) + Math.abs(fontMetrics.ascent);    //绘制文字的基准线baseLine

float topY = baseY + fontMetrics.top;    

float ascentY = baseY + fontMetrics.ascent;    

float descentY = baseY + fontMetrics.descent;    

float bottomY = baseY + fontMetrics.bottom; 

// 绘制文本 ,其中所有坐标均是相对本控件自己的坐标

canvas.drawText( text, baseX, baseY, textPaint); // 第二个参数:从左向右的起始点,第三个参数:文字的baseLine所在的Y轴坐标

重点:android坐标轴的建立是从左向右,从上向下。对于文字的基准线等名词不懂的可以百度搜索FontMetrics。

   本文重点在于讲解垂直方向的文字居中,因为这往往就是难点。