标签:canvas android textview app 博客
如果你想手动在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 text
Rect 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 text
Rect 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
);

Android文本的测量和绘制,布布扣,bubuko.com
标签:canvas android textview app 博客
原文地址:http://blog.csdn.net/kennethyo/article/details/33720589