为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2019-09-18 14:48:08
我正在测量文本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 134D/Test    (  607): Size 11.000000, measureText 149.000000, getTextBounds 148D/Test    (  607): Size 12.000000, measureText 156.000000, getTextBounds 155D/Test    (  607): Size 13.000000, measureText 171.000000, getTextBounds 169D/Test    (  607): Size 14.000000, measureText 195.000000, getTextBounds 193D/Test    (  607): Size 15.000000, measureText 201.000000, getTextBounds 199D/Test    (  607): Size 16.000000, measureText 211.000000, getTextBounds 210D/Test    (  607): Size 17.000000, measureText 225.000000, getTextBounds 223D/Test    (  607): Size 18.000000, measureText 245.000000, getTextBounds 243D/Test    (  607): Size 19.000000, measureText 251.000000, getTextBounds 249
查看完整描述

3 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

我的经验是,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();


查看完整回答
反对 回复 2019-09-18
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

这里是对真正问题的描述:


简单的简单回答是没有开始的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) {

    Rect bounds = new Rect();

    paint.getTextBounds(text, 0, end, bounds);

    int width = bounds.left + bounds.width();

    return width;

}

注意这一点bounds.left- 这是问题的关键。


通过这种方式,您将获得与使用时相同的文本宽度Canvas.drawText()。


并且相同的功能应该是获取height文本:


public int getTextHeight(String text, Paint paint) {

    Rect bounds = new Rect();

    paint.getTextBounds(text, 0, end, bounds);

    int height = bounds.bottom + bounds.height();

    return height;

}

Ps:我没有测试这个确切的代码,但测试了这个概念。


查看完整回答
反对 回复 2019-09-18
  • 3 回答
  • 0 关注
  • 834 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信