hongyang(http://blog.csdn.net/lmj623565791/article/details/44098729)
这篇博客中这段代码
- private void measureText()
- {
- mTextWidth = (int) mPaint.measureText(mText);
- mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
- }
这段代码的含义是啥?获取文字对应的宽高。
Android drawText获取text宽度的三种方式(转载)
- 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);
- public static int getTextWidth(Paint paint, String str) {
- int iRet = 0;
- if (str != null && str.length() > 0) {
- int len = str.length();
- float[] widths = new float[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);
也可以看看这个http://blog.csdn.net/lovexieyuan520/article/details/43153275。
对于canvas.drawText()方法特别注意它的参数,x和y,其实它表示的是文字的“左下角”,并非左上角的那个点,这个要注意。