標籤:canvas android textview app 部落格
翻譯與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);
這幾下就做出了完美置中的文本。悠嘻!