Android文本的测量和绘制

来源:互联网 发布:爬虫怎么找兼职 知乎 编辑:程序博客网 时间:2024/06/13 10:50

翻译与 Chris Banes的博客     原文地址

如果你想手动在Android Canvas上画些什么东西,你最好从绘制文本开始。

文本绘制之前,你需要知道测量文本的绘制位置,计算文本X/Y轴的位置。

                                                                                       

最近我在一款APP中,需要在横向和纵向的画布上绘制一些以文本为中心的文字。于是我用了下面这些代码:

Paint mTextPaint = new Paint();  mTextPaint.setTextAlign(Paint.Align.CENTER); // Center the text// Later when you draw...canvas.drawText(mText, // Text to display          mBounds.centerX(), // Center X of canvas bounds        mBounds.centerY(), // Center Y of canvas bounds        mTextPaint);

我没想到代码的运行后竟然是下面的这个样子:

测量文本

接下来,我尝试定位文本,计算了文本的高宽度,并且修改了绘制文本X轴Y轴的位置:

int mTextWidth, mTextHeight; // Our calculated text bounds  Paint mTextPaint = new Paint();// Now lets calculate the size of the textRect textBounds = new Rect();  mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds);  mTextWidth = textBounds.width();  mTextHeight = textBounds.height();// Later when you draw...canvas.drawText(mText, // Text to display          mBounds.centerX() - (mTextWidth / 2f),        mBounds.centerY() + (mTextHeight / 2f),        mTextPaint);
这一次我们做的已经相当接近了,但是你可以看到文本还是没有居中。

为了确定我没看到的原因,我用Paint.getTextBounds()计算一个矩形,并画在了文本的后面。

正如你看到的,文本的高宽绘制在了计算范围之外。

另一中测量文本的方法

在这个基础点上,我看到Paint另一种计算文本宽度的方法:Paint.measureText()

这个方法只能计算宽度而不能计算高度,因此我尝试结合两种方法:

int mTextWidth, mTextHeight; // Our calculated text bounds  Paint mTextPaint = new Paint();// Now lets calculate the size of the textRect textBounds = new Rect();  mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds);  mTextWidth = mTextPaint.measureText(mText); // Use measureText to calculate width  mTextHeight = textBounds.height(); // Use height from getTextBounds()// Later when you draw...canvas.drawText(mText, // Text to display          mBounds.centerX() - (mTextWidth / 2f),        mBounds.centerY() + (mTextHeight / 2f),        mTextPaint);
这几下就做出了完美居中的文本。悠嘻!

0 0