android canvas.drawText()的研究
阿新 • • 發佈:2019-02-14
這篇部落格中這段程式碼
private void measureText()
{
mTextWidth = (int) mPaint.measureText(mText);
mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
}
這段程式碼的含義是啥?獲取文字對應的寬高。
- String str = "Hello";
- canvas.drawText( str , x , y , paint);
- //1. 粗略計算文字寬度
-
Log.d(TAG, "measureText=" + paint.measureText(str));
- //2. 計算文字所在矩形,可以得到寬高
- Rect rect = new Rect();
- paint.getTextBounds(str, 0, str.length(), rect);
- int w = rect.width();
- int h = rect.height();
- Log.d(TAG, "w=" +w+" h="+h);
- //3. 精確計算文字寬度
- int textWidth = getTextWidth(paint, str);
- Log.d(TAG, "textWidth=" + textWidth);
-
publicstaticint getTextWidth(Paint paint, String str) {
- int iRet = 0;
- if (str != null && str.length() > 0) {
- int len = str.length();
- float[] widths = newfloat[len];
- paint.getTextWidths(str, widths);
- for (int j = 0; j < len; j++) {
-
iRet += (int) Math.ceil(widths[j]);
- }
- }
- return iRet;
- }
measureText()和getTextBounds()方法,那麼這兩個方法的區別是啥?
http://stackoverflow.com/questions/7549182/android-paint-measuretext-vs-gettextbounds
final String someText = "Hello. I believe I'm some text!";
Paint p = new Paint();
Rect bounds = new Rect();
for (float f = 10; f < 40; f += 1f) {
p.setTextSize(f);
p.getTextBounds(someText, 0, someText.length(), bounds);
Log.d("Test", String.format(
"Size %f, measureText %f, getTextBounds %d",
f,
p.measureText(someText),
bounds.width())
);
}
這篇部落格中這段程式碼
canvas.drawText(mText, mTextStartX, getMeasuredHeight() / 2
+ mTextBound.height() / 2, mPaint);
檢視Android Canvas drawText實現中文垂直居中(http://blog.csdn.net/hursing/article/details/18703599)說的很清楚。
也可以看看這個http://blog.csdn.net/lovexieyuan520/article/details/43153275。
對於canvas.drawText()方法特別注意它的引數,x和y,其實它表示的是文字的“左下角”,並非左上角的那個點,這個要注意。