猿问

Android Paint:.measureText()vs .getTextBounds()

我正在测量文本Paint.getTextBounds(),因为我有兴趣获得要渲染的文本的高度和宽度。但是,实际呈现的文本总是比填充.width()的Rect信息宽一些getTextBounds()。


令我惊讶的是,我进行了测试.measureText(),发现它返回了一个不同的(更高)值。我试一试,发现它是正确的。


为什么他们报告不同的宽度?我怎样才能正确获得高度和宽度?我的意思是,我可以使用.measureText(),但后来我不知道我是否应该相信.height()返回者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())

    );

}

输出显示差异不仅大于1(并且没有最后一刻的舍入误差),而且似乎随着大小而增加(我即将得出更多结论,但它可能完全取决于字体):


D/Test    (  607): Size 10.000000, measureText 135.000000, getTextBounds 134

D/Test    (  607): Size 11.000000, measureText 149.000000, getTextBounds 148

D/Test    (  607): Size 12.000000, measureText 156.000000, getTextBounds 155

D/Test    (  607): Size 13.000000, measureText 171.000000, getTextBounds 169

D/Test    (  607): Size 14.000000, measureText 195.000000, getTextBounds 193

D/Test    (  607): Size 15.000000, measureText 201.000000, getTextBounds 199

D/Test    (  607): Size 16.000000, measureText 211.000000, getTextBounds 210

D/Test    (  607): Size 17.000000, measureText 225.000000, getTextBounds 223

D/Test    (  607): Size 18.000000, measureText 245.000000, getTextBounds 243

D/Test    (  607): Size 19.000000, measureText 251.000000, getTextBounds 249

陪伴而非守候
浏览 835回答 3
3回答

慕码人8056858

我的经验是,getTextBounds将返回封装文本的绝对最小边界矩形,而不一定是渲染时使用的测量宽度。我还想说measureText假设一行。为了获得准确的测量结果,您应该使用它StaticLayout来渲染文本并拉出测量结果。例如:String text = "text";TextPaint textPaint = textView.getPaint();int boundedWidth = 1000;StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);int height = layout.getHeight();

慕田峪7331174

这里是对真正问题的描述:简单的简单回答是没有开始的Paint.getTextBounds(String text, int start, int end, Rect bounds)回报。也就是说,要获得将通过使用getTextBounds()中的相同 Paint对象调用而设置的文本的实际宽度,您应该添加Rect的左侧位置。像这样的东西:Rect(0,0)Canvas.drawText(String text, float x, float y, Paint paint)public int getTextWidth(String text, Paint paint) {&nbsp; &nbsp; Rect bounds = new Rect();&nbsp; &nbsp; paint.getTextBounds(text, 0, end, bounds);&nbsp; &nbsp; int width = bounds.left + bounds.width();&nbsp; &nbsp; return width;}注意这一点bounds.left- 这是问题的关键。通过这种方式,您将获得与使用时相同的文本宽度Canvas.drawText()。并且相同的功能应该是获取height文本:public int getTextHeight(String text, Paint paint) {&nbsp; &nbsp; Rect bounds = new Rect();&nbsp; &nbsp; paint.getTextBounds(text, 0, end, bounds);&nbsp; &nbsp; int height = bounds.bottom + bounds.height();&nbsp; &nbsp; return height;}Ps:我没有测试这个确切的代码,但测试了这个概念。
随时随地看视频慕课网APP

相关分类

Android
我要回答