您的位置:首页 > 移动开发 > Android开发

android canvas.drawText()的研究

2015-11-19 15:52 357 查看
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);

查看Android Canvas drawText实现中文垂直居中(http://blog.csdn.net/hursing/article/details/18703599)说的很清楚。
也可以看看这个http://blog.csdn.net/lovexieyuan520/article/details/43153275。

对于canvas.drawText()方法特别注意它的参数,x和y,其实它表示的是文字的“左下角”,并非左上角的那个点,这个要注意。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: