1. 程式人生 > >android canvas.drawText()的研究

android canvas.drawText()的研究

這篇部落格中這段程式碼

private void measureText()  
{  
    mTextWidth = (int) mPaint.measureText(mText);  
    mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);  
}  

這段程式碼的含義是啥?獲取文字對應的寬高。
  1. String str = "Hello";  
  2. canvas.drawText( str , x , y , paint);  
  3. //1. 粗略計算文字寬度
  4. Log.d(TAG, "measureText=" + paint.measureText(str));  
  5. //2. 計算文字所在矩形,可以得到寬高
  6. Rect rect = new Rect();  
  7. paint.getTextBounds(str, 0, str.length(), rect);  
  8. int w = rect.width();  
  9. int h = rect.height();  
  10. Log.d(TAG, "w=" +w+"  h="+h);  
  11. //3. 精確計算文字寬度
  12. int textWidth = getTextWidth(paint, str);  
  13. Log.d(TAG, "textWidth=" + textWidth);  
  14.     publicstaticint getTextWidth(Paint paint, String str) {  
  15.         int iRet = 0;  
  16.         if (str != null && str.length() > 0) {  
  17.             int len = str.length();  
  18.             float[] widths = newfloat[len];  
  19.             paint.getTextWidths(str, widths);  
  20.             for (int j = 0; j < len; j++) {  
  21.                 iRet += (int) Math.ceil(widths[j]);  
  22.             }  
  23.         }  
  24.         return iRet;  
  25.     }  

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,其實它表示的是文字的“左下角”,並非左上角的那個點,這個要注意。