确定文字的宽高
- 获取文字宽度
TextPaint.setTextSize(mBiggerTextSize);
mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
int textWidth = (int) mTextPaint.measureText(currentNumber); // 确定文字宽度
- 获取文字高度
Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
leading = paint.getFontMetrics().leading; //其中baseline属性对应fontMetrics.leading
top = paint.getFontMetrics().top;
ascent = paint.getFontMetrics().ascent;
descent = paint.getFontMetrics().descent;
bottom = paint.getFontMetrics().bottom;
通过FontMetrics获取文字高度相关属性
Tips:
(1) 还有一种方式获取宽高,但是不是非常准确,仅获取显示文字的最小范围
Rect rect = new Rect();
mPaint.getTextBounds(text, 0, test.length(), rect);
int width = rect.width();//文字宽
int height = rect.height();//文字高
(2) 最后调用canvas.drawText(text, dx, dy, mTextPaint);进行绘制,其中dx为文字最边距,dy为文字对应的baseline高度
确定多行文字的宽高
通过StaticLayout来计算,可以做出限制宽高的效果
StaticLayout myStaticLayout = new StaticLayout(text, mTextPaint, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
myStaticLayout.draw(canvas);
// layout的对其方式,有ALIGN_CENTER, ALIGN_NORMAL, ALIGN_OPPOSITE 三种。